0
\$\begingroup\$

I have been trying to find a solution for the last couple of hours so please hear me out. At first I got a NullReferenceException, which I resolved(?) by initializing the class first (This is my problem! I can't seem to initialize my class sucessfully). However, here are my next errors. I tried using the new keyword, which resulted in You are trying to create a MonoBehaviour using the 'new' keyword. Next I tried GetComponent<>(), which resulted in a CS0120, that I didn't know how to fix. The AddComponent<>(), resulted in a CS0103 The name AddComponent does not exist in the current context. What I tried next was GameObject.AddComponent<>(), which threw a CS0120, and gameObject.Addcomponent<>() which threw a CS0236.

Here is my code for the class I am trying to initialize if it should be needed:

public class Dialogue : MonoBehaviour {
public TextMeshProUGUI textDisplay;
public string[] sentences;
private int index;
public float typingSpeed;

public GameObject continueButton;

void Update() {
    if (textDisplay.text == sentences[index]) {
        continueButton.SetActive(true);
    }
}

public IEnumerator Type() {
    foreach (char letter in sentences[index].ToCharArray()) {
      textDisplay.text += letter;
      yield return new WaitForSeconds(0.01f);
    }
}

public void NextSentence() {
    continueButton.SetActive(false);

    if (index < sentences.Length - 1) {
        index++;
        textDisplay.text = "";
        StartCoroutine(Type());
    } else {
        textDisplay.text = "";
        continueButton.SetActive(false);
    }
  }
}

Here is from where I tried to initialize:

public class Mace : MonoBehaviour {
//Dialogue dialogue = gameObject.AddComponent<Dialogue>();

private void OnTriggerEnter2D(Collider2D otherCollider) {
    if (otherCollider.CompareTag("Player")) {
        StartCoroutine(dialogue.Type());
    }
}

}

\$\endgroup\$
0
\$\begingroup\$

Your main problem here is that you're trying to put code into a field initializer that is not valid there. As your error messages are telling you, field initializers are not allowed to reference non-static members, because when they run, by definition, the instance they're running for hasn't finished initializing yet!

You have two main options (which are already explained thoroughly here — this is why it's important to read thoroughly when someone links you to an existing duplicate Q&A)

1. Make your reference public and populate it in the Unity Inspector interface before you run your game. Then the variable will be filled in by Unity's deserializer automatically when your object loads/spawns.

public class Mace : MonoBehaviour {

    // This adds a field you can set in the Inspector.
    public Dialogue dialogue;

    void Start() {
        if(dialogue == null)
            Debug.LogError("You forgot to populate the dialogue field before running!");
    }

    // ...the rest of your script goes here.

}

2. Fetch/add the component you need when this script "boots up," in Start or Awake:

public class Mace : MonoBehaviour {

    // We can leave this private if wiring it up ourselves.
    Dialogue _dialogue;

    void Awake() {
        // Create a new dialogue component attached
        // to the same object as this script, 
        // and cache a reference to it.
        _dialogue = AddComponent<Dialogue>();
    }

    // ...the rest of your script goes here.

}

Myself, if the script only makes sense when there's a specific dependency present, I like to make that dependency visible to Unity so it can enforce it for me at edit time, then at runtime I can just pick up a reference to the component I know will be there waiting for me;

// This attribute tells Unity to add a Dialogue
// component anytime I add a Mace component.
[RequireComponent(typeof(Dialogue))]
public class Mace : MonoBehaviour {

    Dialogue _dialogue;

    void Awake() {
        // Since the editor enforces our dependency,
        // we can be confident it's there to "Get"
        _dialogue = GetComponent<Dialogue>();
    }

    // ...the rest of your script goes here.

}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.