I’ve been researching this for a while but I have not found anything or any way to accomplish this.
Basically I have some bullet prefabs which get instantiated every time the user fires the guns. The problem is when this happens, these bullet prefabs have a script attached which determines when they get destroyed. They share values between every object. I need them to disappear/destroy themselves when they have reached the end of their individual lifespan or range.
My research turned up these two answers, one of which was almost exactly what I needed but the answer that person received did not work for me.
The one that would have worked:
and the other resource I found:
The first one which was almost helpful tried this code:
GameObject NewBasicStarPrefab =(GameObject) Instantiate(BasicStarPrefab, position, Quaternion.identity);
NewBasicStarPrefab.name = "BasicStar"; // Rename the clone to BasicStar
// Access the clones script and send some variables to it
NewBasicStarPrefab.SendMessage("SetStarNumber",CurrentStarNumber);
NewBasicStarPrefab.SendMessage("SetStarType",CurrentStarType);
}
So then I tried the SendMessage function to call a function in my script attached to the prefab but it did not achieve what I needed.
This is my DestroyBullet2 C# script:
using UnityEngine;
using System.Collections;
public class DestroyBullet2 : MonoBehaviour {
public float LIFESPAN;
public float WEAPON_RANGE;
public float distanceTraveled;
public float timeCreated;
public float timeAlive;
public float rateOfMovement;
public void SetValues() { //The function which should have reset the values when called from another by SendMessage()
distanceTraveled = 0.0f;
timeCreated = Time.time;
timeAlive = 0.0f;
}
void Start () {
timeCreated = Time.time; //Store the time this object was created at.
}
void Update () {
/* Scripts if attached to a prefab do not have separate/individual variable values!
* They pass the same values the last one had, along with it! */
//I need to store the time since the object was created. When the time since creation exceeds LIFESPAN then destroy it.
timeAlive += Time.deltaTime; //Update the timeAlive variable
distanceTraveled = Time.time * rateOfMovement; //Compute distance traveled
if ( (Time.time - timeCreated) > LIFESPAN || distanceTraveled > WEAPON_RANGE) { //If time since creation is greater than the LIFESPAN,
//OR the distance traveled is greater than the range we destroy the object.
Destroy (gameObject);
print ("Destroyed Object. Time was: " + Time.time + " and the difference is: " + (Time.time - timeCreated) + " Distance traveled was: " + distanceTraveled );
}
}
}