- Home /
Why wont this work? (I've done similar 1000 times fine)
I've done this get component stuff 1000 times and its worked just fine, but its been a while so I don't remember if this is right. I would like it to work without making a public variable for the player but that wasn't working either. I am trying to access the player's script NPCDropper when the health equals Zero. and set the boolean to true.
public class EnemyHealth : MonoBehaviour {
public int curHP;
public int maxHP;
public GameObject player;
void Start ()
{
curHP = maxHP;
}
void Update ()
{
if(curHP <= 0)
{
var npcD = player.GetComponent<NPCDropper>();
npcD.weShouldDrop = true;
}
}
}
What's not working? Are you getting a NullReferenceException?
A few things to note:
You can use "var" in C#. So you're fine there.
Since you're not going to be calling GetComponent() every frame, it's fine to declare it in Update.
When you post a question or answer, there's a "101/010" button. Click this before entering code to format it properly.
Whenever you call GetComponent(), you should almost always check that the return value is valid (not null). You can skip this if you use the RequireComponent directive. For example:
[RequireComponent(typeof(NPCDropper))]
public class EnemyHealth : $$anonymous$$onoBehaviour {
...
}
In this case, you're guaranteed that it will have an NPCDropper, so GetComponent() should never return null.
Answer by programmrzinc · Jan 29, 2014 at 10:28 PM
You are mixing unityscript and C. you are using var to declare a variable.
public int curHP;
public int maxHP;
public GameObject player;
void Start ()
{
curHP = maxHP;
}
void Update ()
{
if(curHP <= 0)
{
NPCDropper npcD = player.GetComponent<NPCDropper>();
npcD.weShouldDrop = true;
}
}
}
http://msdn.microsoft.com/en-us/library/bb383973.aspx
Just to clarify, you can use var in c#. Good answer though.