c# - 通过脚本找对撞机

标签 c# unity3d

我有一个 list 脚本,我需要找到一个游戏对象并获取它的组件(碰撞器),然后启用它。这是我的代码,你能告诉我哪里出错了吗。

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

    }
}

最佳答案

看这个:

public GameObject Ending;

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

它不会工作因为EndingGameObject 的一种但你正在分配 Collider2D当你这样做的时候Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>;

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

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

但是既然你想找一个Collider2D不是GameObject改变

public GameObject Ending;

public Collider2D Ending;

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

通知()我在最后添加因为 GetComponent是一个函数。

关于c# - 通过脚本找对撞机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53056283/

相关文章:

c# - 无法测试 SmtpClient.TimeOut

c# - 无法在 Razor 中使用变量设置 DropdownList 名称

c# - [XmlType(AnonymousType = true)]

unity3d - AR对象不应随AR Camera Vuforia Unity3d一起移动

c# - 协程是Unity3D中的新线程吗?

c# - “The name '来源' does not exist in the current context [Assembly-CSharp]”,

android - Building Gradle项目失败

c# - 当声明了 using 语句时,为什么有人会在代码中完全限定对象?

使用 Select 或Where 的 C# 谓词不起作用

Android - 在 Activity 中嵌入 Unity3d 场景 - 需要注销接收器吗?