1

I have a Unity project in which the door is set to the GameObject "Door". It is fine and set in the editor (i.e. when I'm not playing it), but as soon as I hit play, it turns to "None (GameObject)". My script uses the Rigidbody component of the door, but I access that through the script. Do I need to reference the Rigidbody component instead?

Why is it doing this?

using UnityEngine;

public class GameManager : MonoBehaviour {

    public GameObject door;

    void Start ()
    {
        door = GameObject.Find("Door1");
    }

    public void NextLevel () {
        Debug.Log("open");
        door.GetComponent<Rigidbody>().AddForce(0, 0, 500);
    }
}

1 Answer 1

2

It could be the lifecycle functions of the script overriding the reference. Try to attach the script in your question, if you couldn’t, check the Awake, Start, Update or FixedUpdate functions, if it is set back to null by typo.

Sign up to request clarification or add additional context in comments.

8 Comments

Yeah, the script is overriding the reference. I see the problem now. Thanks!
Now I get to see your code, please note that 'GetComponent()' is a very slow process, assuming that your the 'rigidbody' of the 'door' won't change during the gameplay, it should be placed in 'Start()'.
So I should make a variable referencing the rigidbody component and apply a force to that instead?
yes. Make a 'private Rigidbody doorRB' field in the class, then, in 'Start()', 'doorRB = door.GetComponent<Rigidbody>();'
Thanks, that will help. Also, do you have any thoughts on this problem I have? - stackoverflow.com/questions/52017955/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.