Really basic problem, I feel retarded (help)

I have 2 classes:

public class Agent : MonoBehaviour {
    private FSM brain;

    void Start ()
    {
        //Create the FSM that will control this agent
        brain = new FSM (this);
    }
}
public class FSM
{
    //Agent this FSM is attached to
    private Agent agent;

    //Constructor
    public FSM (Agent FSMOwner)
    {
        agent = FSMOwner;
        Debug.Log (agent);
    }
}

So I have an empty game object which has the Agent script on it. When the program starts, the Agent script instantiates a new FSM class. In the FSM constructor it debugs the agent, but it keeps returning null.

So how do I pass the Agent class to the FSM class so they can communicate with eachother?

What do you mean by it returns null exactly? Is it because the Debug outputs “false”?

Try debuging agent == null instead.

I’d say it’s probably logging “True”. This would be expected. Unity overrides the implicit boolean operator to check for null in order to mimic the JS style of testing “does this thing exist”

If it’s debugging true it wouldn’t mean it’s null though. I’m not sure if agent is actually null or OP thinks it is.

@OP: that should work. What exactly are your errors? When are they thrown (if there’s errors thrown), where does null get debugged, when does this happen?

No it wouldn’t. It would log true if it wasn’t null. For the same reason that this works:

var thing = GetComponent<Thing>();
if (thing)
{
    thing.Foo();
}

Of course this is assuming that the ToString() override for MonoBehaviour logs true/false at all - which would be surprising if it did.

Debug.Log(obj) logs “Null” if obj is null for any type.

1 Like