如果我想实时访问这个list呢
时间: 2023-08-28 22:05:30 浏览: 32
如果您希望实时访问Cup脚本中的public list,并且在这个list发生变化时得到通知,您可以使用事件(Event)来实现。
首先,在Cup脚本中定义一个事件,用于通知其他脚本该list发生了变化:
```csharp
// 在Cup脚本中
public class Cup : MonoBehaviour
{
public event Action<List<YourType>> ListChanged;
public List<YourType> publicList;
// 在publicList发生变化时触发事件
private void OnListChanged()
{
if (ListChanged != null)
{
ListChanged(publicList);
}
}
// 其他操作publicList的方法...
}
```
然后,在其他脚本中订阅该事件,并实现事件触发时的逻辑:
```csharp
// 在其他脚本中
public class OtherScript : MonoBehaviour
{
public Cup cupInstance;
void Start()
{
// 订阅Cup脚本的ListChanged事件
cupInstance.ListChanged += OnListChanged;
}
// 事件触发时的逻辑
private void OnListChanged(List<YourType> updatedList)
{
// 在这里可以使用updatedList做进一步的操作
}
void OnDestroy()
{
// 在脚本销毁时取消订阅事件,防止内存泄漏
cupInstance.ListChanged -= OnListChanged;
}
}
```
这样,在Cup脚本中的public list发生变化时,会触发ListChanged事件,并在其他脚本中执行相应的逻辑。通过这种方式,您可以实时访问并响应Cup脚本中的list的变化。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)