Hi, I’ve been searching around but still haven’t found the answer yet. I have random spawns of a prefab enemy which isn’t present when the scene starts but spawns shortly thereafter which contains a single variable which can be either 0 or 1. There can be multiple spawns at once so how do I obtain each unique variable tied to the specific prefab for OnTriggerEnter?
If I place an enemy in the scene when it starts I can use GetComponent but when others spawn it isn’t a unique value and is the value of this first enemy.
I’m using C# and any help is appreciated. Thanks
Is it a static variable? That’s the only explanation for why every instance would share the same value.
I have it as a public float
Can you post some code snippets of when you set the variable and when you check the variable?
//Player Script
using UnityEngine;
using System.Collections;
public class PlayerCode : MonoBehaviour {
public EnemyCode getNumber;
private float retainNumber;
void OnTriggerEnter (Collider other) {
getNumber = GameObject.Find (“Enemy”).GetComponent ();
retainNumber = getNumber.randomNumber;
}
}
//Enemy Script
using UnityEngine;
using System.Collections;
public class EnemyCode : MonoBehaviour {
public float randomNumber;
void Awake (){
float randomNumber = (Random.Range (0, 2));
}
}
Well of course with GameObject.Find(“Enemy”), you’re always going to find the same enemy. You’re searching the hierarchy for a specific object.
Why not grab the info from the Collider object handed to OnTriggerEnter? Something like:
void OnTriggerEnter(Collider other)
{
EnemyCode enemyCode = other.gameObject.GetComponent<EnemyCode>();
if(enemyCode != null)
{
retainNumber = getNumber.randomNumber;
}
}
OK, this works but in the EnemyScript, the values in the inspector are by default 0 and this is the return value I get and not the randomNumber on Awake. Any suggestions?