- Home /
How to access Instantiated GameObject's attached script's values?
I have a CrewSpawner.cs to instantiate crews available to hire, which works.
crew = Instantiate(prefab) as GameObject;
crew.name = "crew1";
The crews have a prefab with a component CrewStats.cs:
using UnityEngine;
using System.Collections;
public class CrewStats : MonoBehaviour {
public int fishingSkill;
void Start () {
fishingSkill = Random.Range(1, 11);
}
}
How can I (from a 3rd script) access the instantiated's .fishingSkill? With
public GameObject crew;
public Text text;
void Update () {
crew = GameObject.Find("crew1");
text.text = crew.name;
}
I can get and display it's name, no problem but using crew.fishingSkills gives the error
Assets/Scripts/ShowCrewSkill.cs(16,26): error CS1061: Type `UnityEngine.GameObject' does not contain a definition for `fishingSkills' and no extension method `fishingSkills' of type `UnityEngine.GameObject' could be found (are you missing a using directive or an assembly reference?)
16,26 is the fishingSkills part of crew.fishingSkills obviously.
When I type "crew." I already see that none of the CrewStats things are in the dropdown menu, nor is CrewStats itself, like so: crew.CrewStats. In the Inspector I can see the crew1 object's fishingSkill etc, so they do get created as planned.
Answer by Mmmpies · Feb 04, 2015 at 03:09 PM
set a private CrewStats reference and then use GetComponent.
private CrewStats myCrewStats;
crew = GameObject.Find("crew1");
myCrewStats = crew.GetComponent<CrewStats>();
You can then reference the fishingSkill with myCrewStats.fishingSkill