简体   繁体   English

从组件gameObject访问容器gameObject

[英]Accessing container gameObject from component gameObject

  1. I created a GameObject and named it "sensor". 我创建了一个GameObject ,并将其命名为“ sensor”。 I then added a BoxCollider and a script (script_sensor) to sensor. 然后,我向传感器添加了BoxCollider和脚本(script_sensor)。

  2. Then I created another GameObject and named it "taxi". 然后,我创建了另一个GameObject ,并将其命名为“ taxi”。 I added a script (script_taxi) to taxi and created a public Collider2D in the script. 我在出租车上添加了一个脚本(script_taxi),并在该脚本中创建了一个公共Collider2D

  3. Then I assigned the sensor GameObject to taxi's public Collider2D . 然后,我将传感器GameObject分配给出租车的公共Collider2D

  4. And now, i want to access script_taxi from script_sensor . 而现在,我想访问script_taxiscript_sensor

Basically, How can i access script_taxi (Box 1 on the image), from script_sensor (Box 2)? 基本上,我如何从script_sensor (框2)访问script_taxi (图像上的框1)?

Check the image to understand better. 检查图像以更好地理解。

Ps: When i spam taxi prefabs, every sensor object should be able to find it's own container gameobject(taxi). 附言:当我向出租车预制件发送垃圾邮件时,每个传感器对象都应该能够找到它自己的容器gameobject(taxi)。

If you want to access script_taxi from script_sensor , you need some type of reference to script_taxi inside script_sensor . 如果要从script_sensor访问script_taxi ,则需要在script_sensorscript_taxi某种类型的引用。 You can then use GetComponent . 然后,您可以使用GetComponent You could also use a variation of GameObject.Find , however these calls can be expensive. 您还可以使用GameObject.Find的变体,但是这些调用可能会很昂贵。

public class script_sensor : MonoBehavior {
    [SerializeField]
    private GameObject taxi;

    private script_taxi taxiScript;

    void Start() {
       taxiScript = taxi.GetComponent<script_taxi>();
    }

}

Also it is recommended to follow C# naming conventions . 另外,建议遵循C#命名约定

script_sensor => Sensor

script_taxi => Taxi

public Collider2D col; => [SerializeField] private Collider2D col;

Or with GameObject.Find() to find the taxi GameObject like this: 或使用GameObject.Find()查找出租车的GameObject,如下所示:

    script_taxi taxi;

    void Awake() 
    {    
        taxi = GameObject.FindWith("taxi").GetComponent<script_taxi>();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM