Answer the question
In order to leave comments, you need to log in
What to do if Unity throws NullReferenceException: Object reference not set ot an instance of an object?
I did a platformer according to the tutorial, and when it came to the implementation of bullets, the unit started throwing an error NullReferenceException: Object reference not set ot an instance of an object when trying to shoot, and pointed to a part of the code
public void Shoot()
{
Vector3 bulletspawn = transform.position; bulletspawn.y += 0.3f;
State = CharState.Shoot;
Instantiate(bullet, bulletspawn, bullet.transform.rotation);
}
private Bullet bullet;
private void Awake()
{
bullet = Resources.Load<Bullet>("Bullet");
}
public class Bullet : MonoBehaviour
{
private float speed = 10.0f;
private Vector3 direction;
public Vector3 Direction { set { direction = value; } }
private SpriteRenderer sprite;
private void Awake()
{
sprite = GetComponentInChildren<SpriteRenderer>();
}
private void Start()
{
Destroy(gameObject, 1.4f);
}
private void Update()
{
transform.position = Vector3.MoveTowards(transform.position, transform.position + direction, speed * Time.deltaTime);
}
}
Answer the question
In order to leave comments, you need to log in
Theoretically, you are loading the Bullet component class from some Bullet prefab.
And it remains without a GameObject, and therefore without a transform
Link to the prefab in the editor by dragging it into the field
AND instantiate without loading.
bullet = Resources.Load<Bullet>("Bullet");
public GameObject bullet;
Instead of
private Bullet bullet;
private void Awake()
{
bullet = Resources.Load<Bullet>("Bullet");
}
public GameObject bulett;
public GameObject bullet;
void Start(){
StartCoroutine(SpawnBullet());
}
IEnumerator SpawnBullet()
{
//в while нужно обязательно указать условие, при котором циклы будет выполняться.Если будет while(true), то это будет бесконечный цикл.
while (true)
{
Instantiate(bullet, new Vector3(3 координаты через запятую. пример: 0f, 0f, 0f), Quaternion.identity);
yield return new WaitForSeconds(время через которое будет спавниться пуля пример: 5f);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question