Passing an object as an argument

Hey everyone, I need to pass a gameObject (of type “Conversation”) In this method. This is in my Enemy script. The following is all the snippets you need to know (But there is more inside each script)

“Enemy” Script:

 [SerializeField] Conversation behaviour;

  private void Caught()
    {
        deceit.InitiateDeceit(behaviour);
    }

“Deceit” Script:

 public void InitiateDeceit(Conversation behaviour)
    {
        //First, the enemy initiates the conversation
        enemySpeech.text = behaviour.getFirstEnemyLine();
    }

And the parameter (Named “behaviour” in the method parameter) “Conversation” script:

    public string getFirstEnemyLine()
    {
        [SerializeField] string[] enemyLines = new string[3];

        return enemyLines[0];
    }

The reason is that each enemy has a different object of type conversation that has different lines, therefore each enemy can have a different conversation with the player. I currently get the following error:

NullReferenceException: Object reference not set to an instance of an object
Deceit.InitiateDeceit (Conversation behaviour) (at Assets/Scripts/Deceit.cs:30)
Enemy.Caught () (at Assets/Scripts/Enemy.cs:133)
Enemy.Update () (at Assets/Scripts/Enemy.cs:56)

Is there a better way to do this? This is my very first unity project.

Thank you!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that

Referencing variables, fields, methods (anything non-static) in other script instances:

REMEMBER: it isn’t always the best idea for everything to access everything else all over the place. For instance, it is BAD for the player to reach into an enemy and reduce his health.

Instead there should be a function you call on the enemy to reduce his health. All the same rules apply for the above steps: the function must be public AND you need a reference to the class instance.

That way the enemy (and only the enemy) has code to reduce his health and simultaneously do anything else, such as kill him or make him reel from the impact, and all that code is centralized in one place.

I tried

Debug.Log(behaviour);

And look at this:

It’s Null, and not null at the same time? I’m very confused.

Sounds like maybe you put that script either on more than one GameObject, or twice on the same GameObject.

You can search the scene window for a script by typing the exact name of the class in the search / filter field.

Hahahah Yep! It was hiding in my canvas for some reason. Thanks!

I’m going to move your post to the scripting forum too, it’s nothing to do with 2D.

Please post there in the future for general scripting questions etc.