- Home /
Transfering variable between gameojects and scripts
When one of my my mobs in the scene dies, I want it to tell a script on a completely different object to add one to the count of dead eneies. I've tried GetComponent and Static variable with little success. I'm coding in C#, thanks for any help.
Answer by clunk47 · Dec 03, 2013 at 05:43 PM
There are indeed many ways to do this. Here's an example. In this example project, I have 2 cubes in my scene somewhere in front of my camera. I have an empty gameObject in the scene named "Scripts", with "EnemyList" class attached. Each cube has "Enemy" component attached. Each "Enemy" is added to the list in "EnemyList". In the example, you click on each object that is tagged "Enemy" to kill it, remove it from the list, and add up dead count. Project is attached to make things more easily understandable if you have any issues.
//EnemyList.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemyList : MonoBehaviour
{
[HideInInspector]
public List<GameObject> enemies = new List<GameObject>();
int dead = 0;
void Update()
{
foreach(GameObject go in GameObject.FindObjectsOfType (typeof(GameObject)))
{
if(go.tag == "Enemy" && !enemies.Contains(go) && !go.GetComponent<Enemy>().dead)
enemies.Add (go);
if(go.tag == "Enemy" && go.GetComponent<Enemy>().dead && enemies.Contains(go))
{
enemies.Remove(go);
dead++;
}
}
//TESTING PURPOSES
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast (ray, out hit) && Input.GetMouseButtonDown(0))
{
if(hit.collider.GetComponent<Enemy>() && !hit.collider.GetComponent<Enemy>().dead)
hit.collider.GetComponent<Enemy>().dead = true;
}
//END OF TEST
}
void OnGUI()
{
GUILayout.Label("Dead Enemies - " + dead.ToString ());
}
}
//Enemy.cs
using UnityEngine;
using System.Collections;
public class Enemy : MonoBehaviour
{
[HideInInspector]
public bool dead = false;
}
Answer by thaiscorpion · Dec 03, 2013 at 05:35 PM
There are lots of different ways to access variables from other objects scripts, you can check this link for some examples:
Unity Script, Accessing other scripts
The easiest way is to use the GetComponent method and insert the object in the inspector. If you have treid this already you might want to paste your code to see where the problem is.
I was going to write the same thing. Since i cant see the code i am not sure how you are going about sending the variable. You may want to look at sending a message to the object ins$$anonymous$$d of accessing it directly through GetComponent.
Your answer
Follow this Question
Related Questions
GetComponent C# 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Where is the Mistake in my Coin System? 1 Answer
an object reference is required for the non static field error 1 Answer