- Home /
"the object of type transform has been destroyed but you are still trying to access it" problem,
The problem is line 8(null reference)
private void Start()
{
timeBtwShots = startTimeBtwShots;
}
private void Update()
{
if (target.position != null)
{
Vector3 difference = target.position - transform.position;
float rotZ = Mathf.Atan2(difference.y, difference.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
}
if (timeBtwShots <= 0)
{
Instantiate(projectile, shotpoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}else
{
timeBtwShots -= Time.deltaTime;
}
}
}
,
Answer by thomh_unity · Oct 01, 2019 at 08:13 AM
Hi caprariualex,
The error you are seeing means the object you're trying to access has been destroyed somewhere else in your code.
If the error is from line 8 then the only object there is the target. I assume this is a target transform.
It's likely that somewhere else in your code you've called Destroy() with the gameobject that the target transform belongs to.
Try adding a null check on line 8 for the target. Something like:
if (target!=null)
The code you currently have is checking the struct's position for null and will never return false as a transform's position is a struct, which is a value type, and can never be null.
I hope this helps.
Thx. It's worked, but now my enemy continue firing. Any fix?
Try moving your firing code inside the target null check.
if (target.position != null)
{
Vector3 difference = target.position - transform.position;
float rotZ = $$anonymous$$athf.Atan2(difference.y, difference.x) * $$anonymous$$athf.Rad2Deg;
transform.rotation = Quaternion.Euler(0f, 0f, rotZ + offset);
if (timeBtwShots <= 0)
{
Instantiate(projectile, shotpoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
}else
{
timeBtwShots -= Time.deltaTime;
}
}
This way the projectiles are only created when the script has a target.
Your answer
Follow this Question
Related Questions
Why doesn't AddForce work upwards? 0 Answers
I have a problem with coins 1 Answer
How to spawn multiple prefabs - Tilemap 0 Answers