首页 > 解决方案 > Find a colider through script

问题描述

I have an inventory script and I need to find a game object and get its component which is a collider then enable it. Here is my code can you show me where I went wrong.

public GameObject[] Inventory = new GameObject[3];
public Image[] InventorySlots = new Image[3];
public GameObject Ending;

private void Start()
{
   Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>; //this doesn't work
}

public void AddStoryItem(GameObject item)
{
    bool itemAdded = false;
    //to put items in inventory
    for (int i = 0; i < Inventory.Length; i++)
    {
        //check for empty slot
        if (Inventory[i] == null)
        {
            //place item
            Inventory[i] = item;
            InventorySlots[i].overrideSprite = item.GetComponent<SpriteRenderer>().sprite;
            Debug.Log(item.name + " hey you got an item");
            itemAdded = true;
            item.SendMessage("Store");
            break;
        }
    }
    //inventory full
    if (!itemAdded)
    {
        Debug.Log("it's full");
        //enable collider here

    }
}

标签: c#unity3d

解决方案


看到这个:

public GameObject Ending;

private void Start()
{
   Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>; //this doesn't work
}

它不起作用,因为它Ending是一种类型,GameObject但是您在分配Collider2D时分配给它Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>;

这会起作用(因为GameObject.Find返回一个类型GameObject):

Ending = GameObject.Find("End Determination Object");

但是既然要找一个Collider2DGameObject

public GameObject Ending;

public Collider2D Ending;

现在你可以这样做:Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>();

注意()我在最后添加了因为GetComponent是一个函数。


推荐阅读