- Home /
if ( Transform == null) ?? Empty Transform reference
using UnityEngine; using System.Collections;
public class Projectile : MonoBehaviour {
private int rotationSpeed = 100;
private int speed = 3;
public Transform target;
public Transform checkTarget;
private bool ready = false;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (ready){
transform.localRotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.position), rotationSpeed * Time.deltaTime);
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
else{
Destroy(gameObject);
}
if (target == checkTarget){
}
else{
ready = false;
Destroy(gameObject);
}
print(target);
if (target == null){
Destroy (gameObject);
}
}
void OnTriggerEnter(Collider other) {
if (other.CompareTag("Enemy")){
Destroy(gameObject);
print("Destroyed");
other.SendMessage("Damage" , 50);
}
}
public void SetTarget(Transform tar){
ready = true;
target = tar;
checkTarget = target;
}
}
Hello, I want to delete this projectile when the target variable (witch is declared from another object via "SetTarget") is empty, null or however you want to call it.
I know I can delete using many other techniques, like for example checking if its position is the same that the frame before... but i want to know how to do it this way just for the shake of it and I haven't found any post here about it (yes with gameobjects but not with transforms and i haven't been able to adapt it).
Thanks a lot for your help and sorry if this has already been posted, i wasn't able to find it so i hope this one helps someone.
Please edit your post and format your code using the 1010110 icon
Answer by aldonaletto · Aug 11, 2012 at 03:22 PM
I didn't understand exactly what you wanna do, but supposing that you want to destroy the projectile when its target is dead, just change a little your Update function:
void Update () { // check target existence before anything in Update: if (!target){ // if target doesn't exist anymore... Destroy(gameObject); // destroy projectile... return; // and return from Update to avoid accessing a null target } // target still exists - do the other stuff: if (ready){ transform.localRotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(target.position - transform.position), rotationSpeed * Time.deltaTime); transform.Translate(Vector3.forward * Time.deltaTime * speed); } else { Destroy(gameObject); } if (target == checkTarget){ // do something here } else { ready = false; Destroy(gameObject); } } checkTarget = target; }Notice that the target existence checking was moved to the top of Update: if the target doesn't exist anymore, the projectile suicides and returns from Update to avoid errors in the subsequent instructions.