Hello,
I’ve been struggling in these forum / answers for an answer to this for a couple of hours now but nothing seems to work for me for some reason. Even though some answer sound logical, I can’t make it work.
Here’s my code, which based of some other answer, should work:
Separate Script for the enum
public enum CharacterState
{
Walking,
Dialog,
Combat
}
CharController Script
public class mCharWorld : MonoBehaviour
{
public CharacterState CharState;
void Start()
{
CharState = CharacterState.Walking;
}
void Update()
{
if (CharState == CharacterState.Walking)
{
debug.log("Something");
}
}
}
In Another Script
public mCharWorld mCharScript;
public void InitializeDialog()
{
mCharScript.CharState = CharacterState.Dialog;
}
This last script only throw the classic exception “NullReferenceException: Object reference not set to an instance of an object”.
Not sure how it can be null at this point as it would work for any other type of variable.
A bit of help would be appreaciated.
Best regards,
Stupid mistake: It was just not initialized when I though it was done. For those who would get something similar:
mCharWorld mCharScript;
void Start(){
mCharScript = GameObject.Find("MainChar").GetComponent<mCharWorld>();
}
void WhatEver(){
mCharScript.CharState = CharacterState.Dialog;
}
EDIT: You can also obviously make the variable “public” and attach it in the editor for more performance depending on your needs.
I would suggest you to never use GameObject.Find() in Start() function. You can have really bad performance issues on many devices. Not a very clean solution even for one object or for one frame. There are other methods way more efficient and code clean to do the same.
Unity stores all game objects in a scene within a graph data structure. Finding a game object using Find functions requires performing a depth-first search. Performing this search means looking through the entire graph. This graph contains every game object in every scene open in the game.
A depth first search is an algorithm that has O(V+ E) complexity. What this means is that as our graph grows by adding more vertices and edges, it can take longer for us to search through the graph. The more game objects in the scene, the longer it can take for us to find the game object. Game objects further down in the graph will also take longer to find.