是否可以在可编写脚本的对象中使用UnityEvents和/或UnityActions? 我的尝试看起来像这样:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
[CreateAssetMenu(menuName ="Dog", fileName ="New Dog")]
public class Dog : ScriptableObject
{
public string Id;
public string Text;
public UnityEvent WhenFinished;
public GameObject Go;
}
是否可以使脚本化对象保持对层次结构中GO的引用,或者让事件指向层次结构中的侦听器。无论如何,脚本化对象是否可以与层次结构中的逻辑进行通信?
答案 0 :(得分:0)
是和否。 您可以获得SO to GO参考,反之亦然,但仅限于运行时。 在运行时之外,你只能获得一个SO to GO引用,在运行时之外的编辑器中创建的SO不能引用任何游戏对象(它不知道从哪个场景获得GO)。
以下是显示如何实现此目的的代码。
可编写脚本的对象代码
using System;
using UnityEngine;
[CreateAssetMenu(menuName = "Dog", fileName = "New Dog")]
public class Dog : ScriptableObject {
public GameObject Go;
public static event Action<string> ScriptableToGameobjectEvent;
private void Awake() {
EventScript.GameobjectToScriptableEvent += InstanceCreated;
if (Application.isPlaying) {
ScriptableToGameobjectEvent("Dog Created");
}
}
private void InstanceCreated(GameObject go) {
Go = go;
Debug.Log(Go.name);
}
}
游戏对象代码
using UnityEngine;
using System;
public class EventScript : MonoBehaviour {
public static event Action<GameObject> GameobjectToScriptableEvent;
public ScriptableObject myScriptable;
private void Awake() {
Dog.ScriptableToGameobjectEvent += DogCreated;
}
private void Start() {
myScriptable = ScriptableObject.CreateInstance<Dog>();
}
private void DogCreated(string str) {
Debug.Log(str);
GameobjectToScriptableEvent(gameObject);
}
}