gpt4 book ai didi

c# - 试图将一个类的副本/克隆/复制者放入列表中

转载 作者:行者123 更新时间:2023-11-30 16:45:48 24 4
gpt4 key购买 nike

我在使用从 MonoBehavior 派生并附加到 GameObject 的类时遇到问题。当这个 GameObject(“射弹”)与某物发生碰撞时,组件“Effect”应该被复制并存储在被击中目标的 List() 中。任务结束后,射弹应被销毁。

当我运行它时,我在列表中只看到“Missing (Effect)”。我想我只是在列表中分配了一个引用,当射弹被删除时,引用就会丢失。

Projectile GameObject 具有 Effect 和 Projectile 类作为附加组件:

public class Effect : MonoBehaviour {
public float dps = 2f;
public float duration = 2f;
public operatingDelay = 0.1f;
public bool freezing = false;

void Start(){
StartCoroutine("DamageHealRoutine");
}

IEnumerator DamageHealRoutine() {
int goalCount = (int)(duration / operatingDelay);
float partialDamage = dps * operatingDelay;
for (int i = 0; i < goalCount; i++) {
if (dps > 0)
stats.TakeDamage(partialDamage);
else if (dps < 0)
stats.GetHeal(partialDamage);
yield return new WaitForSeconds(operatingDelay);
}

}
}

public class Projectile : MonoBehaviour {
public Effect effect;

private void Awake() {
effect = GetComponent<Effect>(); // not null
}

public void hittedSomething(GameObject go) {
go.GetComponent<Stats>().effects.Add(effect);
// Without destroying, the List entry is assinged accordingly.
Destroy(this.gameObject);
//Became Missing when destroying the Projectile
}
}

目标 GameObject 具有作为附加组件的统计类:

public class Stats : MonoBehaviour {
public List<Effect> effects;
}

Effect 必须是 MonoBehavior 的继承者,因为它应该能够启动协程并且我想改变它的值。

是否有可能在不将效果作为组件添加到目标上的情况下实现这一目标?

编辑1: Missing

最佳答案

Effect has to a inheritor from MonoBehavior, because it should be able to start Coroutines and i want to alter it's values.

Is there a possibility to achieve this without adding the Effect as a component on the target?

。您只需要从您 100% 确定不会被破坏的任何脚本中引用 any MonoBehaviour。我这么说是因为如果它们被销毁,协程可能会停止运行。

在这个例子中,我将从 Stats 脚本中获取引用,但您可以从您希望的任何脚本中获取它。

新的 Stats 脚本:

public class Stats : MonoBehaviour
{

public List<Effect> effects;
private MonoBehaviour mono;

public MonoBehaviour monoRef
{
get
{
return mono;
}
}


// Use this for initialization
void Awake()
{
mono = this;
}
}

新的Effect 脚本。不需要 MonoBehaviour:

public class Effect
{

public float dps = 2f;
public float duration = 2f;
public operatingDelay = 0.1f;
public bool freezing = false;

MonoBehaviour coroutineMono;

public Effect()
{

coroutineMono = GameObject.Find("StatsObj").GetComponent<Stats>().monoRef;
coroutineMono.StartCoroutine("DamageHealRoutine");
}

IEnumerator DamageHealRoutine()
{
int goalCount = (int)(duration / operatingDelay);
float partialDamage = dps * operatingDelay;
for (int i = 0; i < goalCount; i++)
{
if (dps > 0)
stats.TakeDamage(partialDamage);
else if (dps < 0)
stats.GetHeal(partialDamage);
yield return new WaitForSeconds(operatingDelay);
}
}
}

您现在应该使用 Effect effect = new Effect (),它将在没有 MonoBehaviour 的情况下启动协程。

关于c# - 试图将一个类的副本/克隆/复制者放入列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41466522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com