A prefab and script with OnGUI has been added to gameObject.
How to access gameObject from OnGUI?
Or to index (index from TowerPrefab)?
Added to gameObject Script labeled label
public class TowerPrefab : MonoBehaviour { public int index; public static void ViewTowerPrefab() { foreach (TowerPrefab i in TEMP.TOWER.LIST_TOWER_PREFAB) { var prefab = Resources.Load(i.resources_load); GameObject go = Instantiate(prefab) as GameObject; //создаем объект go.AddComponent<Rigidbody>(); go.transform.position = new Vector3(i.vector3.x, i.vector3.y, i.vector3.z); //Добавляется Скрипт с надписью label go.AddComponent<LabelT>(); } .
public class LabelT : MonoBehaviour { private void OnGUI() { Vector3 screenPosition = Camera.main.WorldToScreenPoint(gameObject.transform.position); //Находим позицию объекта на экране относительно мира Vector3 cameraRelative = Camera.main.transform.InverseTransformPoint(transform.position); //Получаем дальность объекта от камеры if (cameraRelative.z > 0) //если объект находится впереди камеры { var dy = 150; var mdy = dy - 10; //Это работает GUI.Label(new Rect(screenPosition.x, Screen.height - screenPosition.y - mdy, 200f, 20f), this.name); mdy = dy - 10; //??? Как получить поле var i = gameObject.GetComponent<TowerPrefab>() as TowerPrefab; //Не работает //Не находит gameObject //NullReferenceException: Object reference not set to an instance of an object //Не работает var ii = gameObject.GetComponent<TowerPrefab>().index; GUI.Label(new Rect(screenPosition.x, Screen.height - screenPosition.y - mdy, 200f, 20f), i.name); } } } .
NullReferenceException: Object reference not set.
.
public static void AddTowerPrefabInListTowerPrefab(int num) { SwitchTowerPrefab(); GameObject gao = new GameObject("tower__" + num); gao.AddComponent<Rigidbody>(); var unit1 = gao.AddComponent<TowerPrefab>(); // unit1.resources_load = TEMP.TOWER.resources_load; var prefab = Resources.Load(TEMP.TOWER.resources_load); unit1.prefab = prefab; // unit1.index = num; //unit1.transform.position = GetVector3ForTowerPrefab(num); TEMP.TOWER.LIST_TOWER_PREFAB.Insert ( num, unit1 );
TowerPrefabis not on the same object asLabelT, so it doesn’t find it. Is not it so? - Alexey ShimanskyTowerPrefabfor everyone or everyone. if for each your own, then why do you have TowerPrefab instantiated by other TowerPrefab. And if one for all, then what's the point in the index? If you just want everyone to add alabel, then why instantiate new ones? - Alexey Shimanskylabel, then why instantiate new ones? - Alexey Shimansky