【发布时间】:2018-01-15 22:27:09
【问题描述】:
Unity有这个问题,但我想我只是在c#方面做错了。
编辑
看起来通过编写代码并存储父类 A 的子类 B,并且说是 A 类类型,通过修改包含 B 类的 A 类类型的变量,我修改了某种混合类A/B 不代表我真正的 B 类脚本
我所做的是,在不同的预制件上有多个脚本。这些脚本中的每一个都代表一个项目,并且都有父级 Usable,这是一个我实际使用的类,就像一个接口,但将来会得到一些东西。
完整的WeaponLaser 和Usable 脚本如下
当玩家越过一个水滴时,我实例化包含这样的脚本的游戏对象(使用预制)
GameObject Item = Instantiate(droppedItem, transform.position, Quaternion.identity);
Item.transform.parent = transform;
usableItem = droppedItem.GetComponent<Usable>();
usableItem.OnUsed += ReleaseItem;
并像这样使用物品
if (usableItem != null)
usableItem.Use(firePoint.position);
问题是,看起来我在使用 Use() 时调用的脚本是另一个版本。
我的意思是,如果我在脚本 WeaponLaser 的顶部设置 int fireCurrentShoot = 10; 然后在 Start 中输入代码,例如我会这样做 fireCurrentShoot = 2;
它将在脚本 WeaponLaser 内部工作,但是当我使用上面的代码调用它时
if (usableItem != null)
usableItem.Use(firePoint.position);
它会显示fireCurrentShoot = 10所以没有修改
结束编辑
你好,
我有一个不明白的遗产问题,我清理了我所有的班级,但我仍然找不到原因。
我有一个 A 类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Usable : MonoBehaviour
{
protected virtual void Start()
{
}
protected virtual void Update()
{
}
public virtual void Use(Vector3 pos)
{
}
protected virtual void Used()
{
}
}
还有一个B类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponLaser : Usable
{
const int SHOOT_AVAILABLE = 5;
const float FIRE_COOLDOWN = 1;
float fireCurrentCooldown = 0.0f;
int fireCurrentShoot = 0;
protected override void Start()
{
base.Start();
Debug.Log("start");
fireCurrentShoot = SHOOT_AVAILABLE;
Debug.Log("fireCurrentShoot" + fireCurrentShoot);
}
protected override void Update()
{
Debug.Log(fireCurrentShoot); // value is = 5
base.Update();
}
public override void Use(Vector3 shootPosition)
{
Debug.Log(fireCurrentShoot);// value is = 0
base.Use(shootPosition);
base.Used();
}
void FireCooldown()
{
}
}
当我调用 Use 时,我的 Debug.Log 展位值为 0...但我希望有 fireCurrentShoot = 5
我这样称呼它 *:
usableItem = droppedItem.GetComponent<Usable>();
usableItem.Use(firePoint.position);
为什么他等于0?
【问题讨论】:
-
我怀疑问题出在继承上。似乎您在某个时候覆盖了该值,或者您只剩下初始值。你什么时候使用
Start?我不明白你为什么期望有5的值。初始值是0为什么应该是5? -
您没有调用
Start- 所以fireCurrentShoot的值不会更新为5。 -
在Unity中,Start是引擎默认调用的,所以调用了,debug确实显示值@MongZhu
-
我的猜测是某些东西正在创建另一个实例。添加一个显式的无参数构造函数并在其中放置一些日志记录。
-
在设置值之前调用它时,启动方法中的 debug.log 怎么可能给出 5?你在你的例子中混合了两条线吗?