Hay all!
Newish Unity user, first time poster
![]()
Anyway, as my topic says, Im trying to pass variables between prefabs.
Bare with me while i try to explain.
I have a Main code(gameobject) that is the start of the program, It spawns prefabs called hero and enemy.
When hero hits enemy, I want to subtract from its health until it eventually does.
example code im using on a (test bed).
public class GameStart : MonoBehaviour
{
public GameObject heroPrefab;
public GameObject enemyPrefab;
private void Start()
{
GameObject Enemy = Instantiate(enemyPrefab, new Vector2(0, 4f), Quaternion.identity);
GameObject Hero = Instantiate(heroPrefab, new Vector2(4, 4f), Quaternion.identity);
}
}
public class Player : MonoBehaviour
{
public Enemy enemy;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
enemy.currenthealth -= 1;
}
}
}
public class Enemy : MonoBehaviour
{
public int currenthealth = 100;
private void Update()
{
Debug.Log("Enemy = " +currenthealth);
}
}
Both Hero and Enemy are inside prefabs.
When I run the program with just game objects in the hierarchy every thing works fine. But as soon as I turn them into prefabs, it stops working.
Ive tried many different solutions, like give them tags etc…
public GameObject Enemy;
Enemy = GameObject.FindGameObjectWithTag("Enemy");
But everything Ive tried will not work bewteen prefabs.
I can remove either gameobject by using similar code.
void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.name == "Enemy(Clone)")
{
Destroy(this.gameObject);
}
}
Any help on this would be greatly appreciated.
Thanks in advance
![]()