I’m working in a scene where there is a camera, a light and a canvas. The camera instanciate some cube in order to create a map when i launch the scene. The problem is : i want to acces to the canvas and be able to modify it in the script i put on my instantiated cube.
So far i’m using FindObjectOfType like this :
You could try: GameObject.Find(“Canvas”).GetComponent().FindChild(“YOUR ELEMENT”).GetComponent();
Or simply adding a serialized field in your script and drag and drop your element in the inspector.
Yeah, this is going to collapse into a steaming mess the moment you add a second canvas to the scene. And there are plenty of reasons to add a second canvas to the scene. While GameObject.Find has a bad rap, I’d suggest using it over relying on FindObjectOfType.
The other alternative is to use FindObjectsOfType and iterate over the results.
Thanx to the quick response guys !
I’m a bit lost with theses functions, i have search how to use them but i can’t do what i want with them, maybe i don’t use them properly …
Maybe if i post all my script it might be useful to understand.
sing UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class CubeContent : MonoBehaviour {
public GameObject Ore;
private Canvas ProtoUI;
private Text[] Infos;
private GameObject ContentOre;
public int posX;
public int posY;
public int EggContent;
public NinjaController[] Ninjas;
// Use this for initialization
void Start () {
EggContent = 0;
Ninjas = null;
}
// Update is called once per frame
void Update () {
//appel des fonctions réseau.
}
void OnMouseDown(){
print ("I've been clicked");
Infos = new Text[8];
ProtoUI = GetComponentInChildren <Can>();
Infos = ProtoUI.GetComponents <Text> ();
print (Infos.Length);
Infos [0].text = posX + " / " + posY;
}
public void CreateOre(){
int[] ValOre;
ContentOre = (GameObject)Instantiate (Ore, new Vector3 (0, 0, 0), transform.rotation);
ValOre = new int[7];
ValOre [0] = 1;
ValOre [1] = 1;
ValOre [2] = 1;
ValOre [3] = 1;
ValOre [4] = 1;
ValOre [5] = 1;
ValOre [6] = 1;
ContentOre.GetComponent<OreData>().setCoordinates (posX, 0, posY);
ContentOre.GetComponent<OreData>().setOreAmount (ValOre);
ContentOre.GetComponent<OreData>().setDisplayed ();
}
public void setPos(int x, int y){
posX = x;
posY = y;
CreateOre ();
// Instantiate (Cube, new Vector3 (x, 0, y), transform.rotation);
}
public void setEggValue(int Amount){
EggContent += Amount;
if (EggContent > 99)
EggContent = 99;
else
EggContent = 0;
}
public int getposX(){
return (posX);
}
public int getposY(){
return (posY);
}
public int getEggVal(){
return (EggContent);
}
public int getNinjaValue(int Number){
if (Ninjas [Number])
return (Ninjas [Number].getStatus());
return (-1);
}
}