Unity C# Methoden von anderen Scripts aus ausschalten?

1 Antwort

a) Mit einer boolschen Variable.

Beispiel:

public class JumpAction : MonoBehavior
{
  public bool CanJump { get; set; } = true;
  
  public void Jump()
  {
    if (!CanJump)
    {
      return;
    }
  
    /* jump ... */
  }
}

public class JumpEnabler : MonoBehavior
{
  public JumpScript jumpAction; // define in inspector

  private void Start()
  {
    jumpAction.CanJump = false;
  }
}

b) Wenn das Skript eh nur eine einzige Methode enthält bzw. seine Aktion in der Update-Methode aufruft, die sonst nichts anderes tut, kannst du genauso gut das enabled-Property nutzen.

Beispiel:

gameObjectWithJumpActionScript.GetComponent<JumpAction>().enabled = false;