- Home /
Can't find gameobjects being spawned getting a nullreferenceexception
I'm trying to call a function in a script attached to a gameobject being spawned but it can't find the object. Here's the script:
void OnTriggerEnter2D (Collider2D col)
{
GameObject Bugspawn = GameObject.Find ("BugbotPrefab");
Debug.Log(Bugspawn);
Transform BugbotTransform = Bugspawn.transform;
// get player position
Vector3 bugbotxposition = BugbotTransform.position;
// If it hits an enemy...
if (col.tag == "Enemy") {
col.gameObject.GetComponent<Bugbot>().HP -= 2;
if (gameObject.transform.position.x > bugbotxposition.x){
col.gameObject.GetComponent<Bugbot>().bumpRight();
}
if (gameObject.transform.position.x < bugbotxposition.x){
col.gameObject.GetComponent<Bugbot>().bumpLeft();
}
}
}
If I leave the enemy on the scene the script works fine but when I use spawners it can't find the object for some reason.
here's the error: NullReferenceException: Object reference not set to an instance of an object Swatter.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/Scripts/Swatter.cs:20) line 20 is Transform BugbotTransform = Bugspawn.transform; but the debug already returns null.
Answer by YoungDeveloper · Apr 24, 2014 at 08:09 AM
Hi, you should rethink your logic and code structure. What is the purpose of finding the go by findbytag, if you are finding it with trigger anyway? Im writing from phone ill be at the office after about 20 mins, ill write you the code.
That's be great, thanks! I was trying to bump the enemy left or right relative to where it got hit to prevent it from overlapping with my player when i gets hit.
Hi, so first of all, almost never use FindBySomething in Update, Trigger or Collision functions, especially is executed every frame. Secondly, you are getting too much components which is unneeded, you could easily do everything with doing it once.
void OnTriggerEnter2D (Collider2D col){
// If it hits an enemy...
if(col.tag == "Enemy"){
col.gameObject.GetComponent<Bugbot>().HitReceived(transform.position); //send our player position (Vector3) to "bug"
}
}
Your Bug:
public void HitReceived(Vector3 playerPos){
RemoveHp(); //remove those 2hp
BumpHandler(playerPos);
}
private void RemoveHp(){
HP -= 2;
}
private void BumpHandler(Vector3 player){
//player x is bigger
if (player.x > transform.position.x){
bumpRight();
}
//player x is smaller
else{
bumpLeft();
}
}
$$anonymous$$aybe this is bit too much object oriented, but this will give you a nice new ideas how to manage and optimize your code.
Thanks man! I really appreciate it! I've been at this for days always getting it wrong.
Your answer
Follow this Question
Related Questions
Find a shader not in the scene 1 Answer
Find with tag throwing an Null exception 1 Answer
script GetComponent, nullReference error 1 Answer
Using Scripts in AssetBundles 0 Answers