This seems to be a common problem but I haven’t found a solution to it yet.
I’m trying to create an enemy that can shoot projectiles at the player, so the projectile is a prefab which has a script named “attack” with the public method “shoot”, and the enemy script has a public variable with the prefab GameObject Attack. Whenever I instantiate a new Attack GameObject atk then call atk.GetComponent() it returns null.
This only happens specifically with instantiated prefabs. When I use an Attack GameObject that’s already on the scene I’m able to get the attack script. It also seems to only apply to scripts, since calling GetComponent on any pre-built components like Rigidbody2D was successful.
Edit: example code that doesn’t work
public class Enemy : MonoBehaviour
{
public GameObject attack; //the Attack prefab
void Start() {}
void Update() {}
void spawnAttack()
{
GameObject a = Instantiate(attack, transform.position, Quaternion.identity);
a.GetComponent<AttackScript>().shoot(new Vector2(10f, 10f)); // this gets null reference exception
}
}
public class AttackScript : MonoBehaviour
{
Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update() {}
public void shoot(Vector2 direction) {
rb.velocty = direction;
}
}
code that does work:
// this works:
public GameObject attack; //the GameObject I dragged on-screen
void Start() {
attack.GetComponent<AttackScript>().shoot(new Vector2(10f, 10f));
}
// this also works:
public GameObject attack; //the Attack prefab
void spawnAttack() {
GameObject a = Instantiate(attack, transform.position, Quaternion.identity);
a.GetComponent<Rigidbody2D>().velocity = new Vector2(10f, 10f);
}
Post your code please, it will be a lot easier
– CasiellTry forcing the type of the prefab to have a
– HelliumAttackcomponent public class Enemy : MonoBehaviour { public AttackScript attack; //the Attack prefab void spawnAttack() { AttackScript a = Instantiate(attack, transform.position, Quaternion.identity); a.shoot(new Vector2(10f, 10f)); } }