- Home /
Assigning a gameObject in the script
I'm sorry but I found it hard to get a good title for what I'm looking for. So, basically I want to assign a gameObject in the script. This is my current script:
public TestHealth playerScript;
private GameObject Player;
void Start() {
playerScript = Player.GetComponent<TestHealth>();
}
public void OnCollisionEnter2D (Collision2D other) {
if(other.gameObject.name == "Player") {
Debug.Log ("BONK");
playerScript.curhp -= 10;
}
}
How can I assign "Player" to playerScript? When I do this by hand in the Unity interface, the game and function works, but I get an error message with a null reference to a gameObject, like the Player object was not assigned. But I believe this is only for the first frame or something. It is really annoying. I would love some insight on this!
Sorry for my lack of experience and depth, I am working hard to improve :)
Answer by Bunny83 · Oct 12, 2014 at 12:20 PM
You simply don't need your "Player" variable at all.
public TestHealth playerScript;
public void OnCollisionEnter2D (Collision2D other)
{
if(other.gameObject.name == "Player")
{
Debug.Log ("BONK");
playerScript.curhp -= 10;
}
}
If you drag your player object onto the "playerScript" variable, Unity automatically assigns the TestHealth component to that variable. If the object you drag doesn't have that component, you can't assign it to that variable. using a GameObject reference and GetComponent in Start is just more complicated and not necessary at all.
Huh.. well, there you go. I get so confused at times. Thank you, kind sir :)
Answer by 767_2 · Oct 12, 2014 at 12:09 PM
use
public GameObject Player;
or
[SerializeField]
private GameObject Player;
This removed the error in the console! I changed it to public, and added the Player object in unity there as well. It was so simple, thank you :)
Answer by tanoshimi · Oct 12, 2014 at 12:10 PM
In your Start() function you need to assign the Player variable. For example:
Player = GameObject.Find("NameOfThePlayerObjectInYourScene");
Your answer
![](https://koobas.hobune.stream/wayback/20220613164930im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Initializing objects with another scripts variables. 1 Answer
Assigning variables in inspector 1 Answer
Distribute terrain in zones 3 Answers