I’ve seen this question asked dozens of times and have yet to find a solution to my problem.
I’m new to JS and Unity as well so bear with me while I explain the situation.
I have two Scripts and a GameObject and a Prefab.
(script1)
The GameObject on GetButtonUp Fire2 (right-click) Instantiates a PreFab. After 15 PreFabs have been created I destroy the first one after each consecutive click.
(script2)
I now want the spawned PreFab to also destroy after a specific collision. The destruction works fine. My problem is that when the PreFab gets destroyed via a collision it doesn’t know it in the script of the GameObject that spawns it.
What I am looking for:
If the object gets destroyed via a collision I want it to tell script1 that it has done so.
my code so far (not sure how to post code in a forum yet):
(Script 1, ‘Creator’, applied to empty gameObject ‘Gun’)
var thePrefab : GameObject;
public var MaxObjectCount = 0;
var ForceX : float = 500.0;
var ForceY : float = 500.0;
var ForceZ : float = 500.0;
function Update () {
//spawn box
if(Input.GetButtonUp("Fire2")){
var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
//velocity of spawned box
instance.rigidbody.AddForce(Vector3(ForceX,0,0));
instance.rigidbody.AddForce(Vector3(0,ForceY,0));
instance.rigidbody.AddForce(Vector3(0,0,ForceZ));
instance.name = "boxSpawn";
//add to the total spawned
MaxObjectCount += 1;
checkhit();
}
}
function checkhit(){
//after 15 box's have spawned kill the next one and create a new one
if(MaxObjectCount == 16){
Destroy(GameObject.Find("boxSpawn"));
//subtract from the total spawned
MaxObjectCount -=1;
}
}
(Script 2, applied to PreFab in Project Pane named ‘BoxPrefab’)
function Update (){
//not sure what to put here
var killCount : Creator = gameObject.GetComponent(Creator);
}
//destroys the spawned box upon collision
function OnCollisionEnter (boxHitKill : Collision) {
if(boxHitKill.gameObject.name == "CollisionWallDestroyer"){
Destroy(GameObject.Find("boxSpawn"));
//where I want to subtract from the variable MaxObjectCount on the script 'Creator'
Creator.MaxObjectCount -=1;
}
}
How can I access the current status of the variable ‘MaxObjectCount’ and affect it in Script2? I’ve read the documentation and a lot of forums posts but have yet to be able to make changes from one script onto another one since the second script is attached to a prefab that hasn’t been spawned yet.
I’m sure the solution is simple, but I am new to the scene and appreciate any help I can get. Thank you in advance!