Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

“the object of type transform has been destroyed but you are still trying to access it”

This is from How to make a Tower Defense game ep 5 [Shooting]

So my problem is that when a target is locked on by 2 different turrets and it is destroyed i get the message from title. Anyone knows a fix for this? {code below} and thank you!

using System.Collections;

using System.Collections.Generic;

using UnityEngine;


public class Bullet : MonoBehaviour

{

  private Vector3 targetPosition;

  private Transform Target;


  public float speed = 70f;

  public GameObject impactEffect;





  public void Seek(Transform _target)

  {

    targetPosition = _target.position;

    Target = _target;

  }



  // Update is called once per frame

  void Update()

  {


    Vector3 dir = targetPosition - transform.position;

    float distanceThisFrame = speed * Time.deltaTime;


    if (dir.magnitude <= distanceThisFrame)

    {

      HitTarget();

      return;

    }


    transform.Translate(dir.normalized * distanceThisFrame, Space.World);


  }


  void HitTarget()

  {

    GameObject effectIns = (GameObject)Instantiate(impactEffect, transform.position, transform.rotation);

    Destroy(effectIns, 2f);


    Destroy(Target.gameObject);

    Destroy(gameObject);

     

  }

}

Answers

Sign In or Register to comment.