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 ); 
  • And your TowerPrefab is not on the same object as LabelT , so it doesn’t find it. Is not it so? - Alexey Shimansky
  • It seems so. I'm trying to combine - codename0082016
  • I don’t understand what you want to do) you should have one TowerPrefab for 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 a label , then why instantiate new ones? - Alexey Shimansky
  • index for the test. Yes. TowerPrefab should be one for all and stored in the list for easier access - codename0082016
  • If you just want everyone to add a label , then why instantiate new ones? - Alexey Shimansky

1 answer 1

How to access gameObject from OnGUI?

If the LabelT script hangs on the same object as TowerPrefab, then:

  int index = this.GetComponent<TowerPrefab>().index; 

But it is better to additionally check if there is this script:

 TowerPrefab tp = this.GetComponent<TowerPrefab>(); if (tp != null) { int index = tp.index; } 

If not, then you need to first find this object:

 TowerPrefab tp = GameObject.Find("имя объекта").GetComponent<TowerPrefab>(); 

And it is better not to look for an object 100 times, when initializing a new object with a LabelT, to pass the TowerPrefab parameter for example.

UPD If you want to have one list for the entire application to access TowerPrefab, you can create either a static class or a singleton with a list and, when initialized, drop the necessary prefabs there.

Since UniUzers usually use the editor to drag prefabs, and since static classes cannot be hung on objects, it is better to use Singleton:

 public class TowerPrefs : MonoBehaviour { private static TowerPrefs _instance; public static TowerPrefs Instance {get {return _instance; }} //таким образом приватное поле будет видно в инспекторе [SerializeField] private TowerPrefab[] storage; //Инициализация единственного экземпляра, если будет два или более // объектов с этим скриптом, то все кроме одного самоуничтожатся. void Awake() { if (_instance == null){ _instance = this; }else{ Destroy(this.GameObject); } } //метод для доступа к объектам списка public TowerPrefab GetTowerPrefab(int index) { return storage[index]; } } 

Then you hang this script on an object, throw prefabs and get access to them from anywhere: TowerPrefs.Instance.GetTowerPrefab (12);

  • If you look at the comments in question, it says there is something wrong with the vehicle ... your GetComponent and !=null will not help ....... ps the main thing is not to get too involved with Find - this is a very difficult operation. - Alexey Shimansky
  • If the vehicle wants to make one single list for the entire application, in this case, you can create a Static class or a Singleton, when you initialize, drop the prefabs there and pull them out of them by index. - Luchunpen