C# 如何使用一些未知类中的公共变量?
我并没有在unity论坛上发表这篇文章,因为我认为c语言比unity语言更相关。 我想射杀一个敌人。 我的敌人是玩家或敌人AI。 玩家有PlayerCombatSystem,敌人的Ai有EnemyCombatController。我使用对象变量使用C# 如何使用一些未知类中的公共变量?,c#,unity3d,C#,Unity3d,我并没有在unity论坛上发表这篇文章,因为我认为c语言比unity语言更相关。 我想射杀一个敌人。 我的敌人是玩家或敌人AI。 玩家有PlayerCombatSystem,敌人的Ai有EnemyCombatController。我使用对象变量使用 GetComponent<ScriptName>() 碰撞器是指我正在碰撞的对象 我可以做些什么来增加我在PlayerCombatSystem或EnemyCombatController中存储的损坏价值?损害是一种公共价值 这是我修复t
GetComponent<ScriptName>()
碰撞器是指我正在碰撞的对象
我可以做些什么来增加我在PlayerCombatSystem或EnemyCombatController中存储的损坏价值?损害是一种公共价值
这是我修复thix的两次尝试
float gotDamage = shotterDamage * (100 / (100 + enemy.GetInstanceID.
float gotDamage = shotterDamage * (100 / (100 + enemy.damage;
Object enemy;
float shotterDamage;
if(shotter.GetComponent<PlayerCombatSystem>() != null)
{
shotterDamage = shotter.GetComponent<PlayerCombatSystem>().damage;
}
else if(shotter.GetComponent<EnemyCombatController>() != null)
{
shotterDamage = shotter.GetComponent<EnemyCombatController>().damage;
}
else
{
Debug.Log("ERROR 0");
}
if (collision.GetComponent<PlayerCombatSystem>() != null)
{
enemy = collision.GetComponent<PlayerCombatSystem>();
}
else if (collision.GetComponent<EnemyCombatController>() != null)
{
enemy = collision.GetComponent<EnemyCombatController>();
}
float gotDamage = shotterDamage * (100 / (100 + enemy
创建一个共享基类,例如
// abstract just makes sure this can't be instanced
// directly but only inherited types
public abstract class CombatBase : MonoBehaviour
{
public float Damage;
}
而不是让两个脚本从这个基类继承
public class PlayerCombatSystem : CombatBase
{
// inherits Damage and everything implemented in CombatBase
// so remove it here
// and here you can extend it with its speicifc behaviour
}
及
而在脚本中,您只需使用
CombatBase enemy;
...
// this will also find either PlayerCombatSystem
// or EnemyCombatController since they are both of type
// CombatBase
enemy = collision.GetComponent<CombatBase>();
...
float gotDamage = shotterDamage * (100 / (100 + enemy.Damage);
另一种选择是使用构造函数,例如:
public class EnemyCombatController : MonoBehaviour
{
public PlayerCombatSystem constructorPlayerCombatSystem ;
//your code
//...
//Damage has changed in the other script (PlayerCombatSystem)
float gotDamage = shotterDamage * (100 / (100 + enemy.constructorPlayerCombatSystem.Damage);
}
当您希望在两个类中使用变量时,将使用创建另一个类的构造函数
我不太了解你的代码的操作,但简单一点,我推断游戏是在另一个或其他脚本中执行的,当检测到震动或击中时,可变伤害会发生变化
假设这个变量在玩家拥有的脚本中,你想在有敌人或敌人的脚本中使用它,或者这个变量在另一个脚本中,你想在另外两个脚本中使用它,你可以创建一个其他类类型的变量并在该类中使用它
请记住,必须在inspector中引用包含类的对象
我希望它能帮助您,或者告诉我我是否理解您的问题有什么错误让它们都继承自同一个基类,然后它会出现吗?我不熟悉它是如何工作的,只是为了理解:在敌人中,你希望在检查员中有一个区域,在那里你可以引用PlayerCombatSystem或EnemyCombatController,并且两者都有公共浮动伤害?是的。他们有。谢谢,我现在无法更改我的代码,但我会尽快检查。
public class EnemyCombatController : MonoBehaviour
{
public PlayerCombatSystem constructorPlayerCombatSystem ;
//your code
//...
//Damage has changed in the other script (PlayerCombatSystem)
float gotDamage = shotterDamage * (100 / (100 + enemy.constructorPlayerCombatSystem.Damage);
}