首页 > 解决方案 > Find a common script that is attached to multiple gameObjects?

问题描述

I have a script that has been attached to multiple gameObjects and this script I am referencing in another script. However when referred, only one gameObject is accessed instead of accessing all. How do I access all the gameObjects that use this script?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckForGrab : MonoBehaviour {

    private OVRGrabber grabber; //the script I try to access
    // Use this for initialization
    void Start () {
        grabber = (OVRGrabber) FindObjectOfType(typeof(OVRGrabber)); // the gameObject the script is attached to
    }
}

标签: c#unity3d

解决方案


如果您想要多个结果,则必须查询多个实例。明显地。

尝试FindObject s OfType。注意's'。


此外,在这种情况下,使用泛型而不是强制转换。

grabbers = FindObjectsOfType<OVRGrabber>();
grabber = grabbers[index];

推荐阅读