c# - 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
}
}
解决方案
看到这个:
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");
但是既然要找一个Collider2D
不GameObject
改
public GameObject Ending;
至
public Collider2D Ending;
现在你可以这样做:Ending = GameObject.Find("End Determination Object").GetComponent<Collider2D>();
。
注意()
我在最后添加了因为GetComponent
是一个函数。
推荐阅读
- php - 图片未在 laravel 媒体库中上传
- javascript - 如何使头像以大格式显示?
- html - 实现css悬停并专注于图标的正确方法
- java - 将数据从 Map 映射到 DTO/VO 对象的有效方式
- twilio - 使用带有 JSON 的 Twilio 验证服务 API
- verilog - 为什么我不能在 Verilog 的“总是”块中将寄存器的内容复制到另一个?
- sql - 如何在SQL中比较不同表中列中的两个字符串
- php - Laravel 查询字符串到路由中的 api 调用
- bazel - 在 Bazel 中使用绝对路径是否安全?
- python - 任何人在以长复杂代码导入图像时遇到问题