C# Unity 3D:撞到其他物体时如何改变变量

3

我想让我的“玩家”在碰到特定对象(在这种情况下是普通立方体)时设置一组变量。我还希望它仅发生一次,不要每次玩家碰到该对象时都添加这些值。

这是我玩家代码声明要更改的变量:

public class PlayerInfo : MonoBehaviour {
public static string Name;
public static int Level;
public static int Health;
public static int Damage;
public static float moveSpeed;

public float turnSpeed;
}

然后我有一个对象,'Player'将从这个对象开始撞击:

public class GiveHero : MonoBehaviour {

private void OnTriggerEnter(Collider other)
{
    //Code to assign Name, Level, Health, Damage, moveSpeed, as set values.
}
}

我需要以下代码将上面的代码分配给值。它们是两个独立的对象,位于两个独立的代码表格中。

提前感谢您的帮助!

3个回答

2
除了按照Yotam的回答更改PlayerInfo变量之外,您还需要一种方法来确保此更改仅发生一次。有多种方法可以做到这一点,其中一些方法可能比其他方法更适合您的项目。您可以尝试以下方法:
  1. 在游戏对象上创建一个布尔变量,当玩家与其碰撞时,该变量将从False变为True。
  2. 一旦游戏对象与玩家发生碰撞并更改了相应的PlayerInfo变量,则销毁该游戏对象。

看起来你没有完成这个答案中的代码编写。你能否更新一下,包括完整的代码片段,并将代码格式化为代码块?谢谢! - Max von Hippel

1
将这些属性标记为static使您的工作变得容易 :-)
例如,降低健康值:
PlayerInfo.Health -= 1;

虽然我不确定将它们设为静态的是否是正确的方法,但这段代码可以在你的情况下工作。


这就是我最初寻找的代码,谢谢!nate_moyer的回复解决了我的另一个问题,它只发生一次。我希望我能将你们两个的回复都标记为正确。虽然我+1了你们两个。 - Christian Dimaggio

0
我建议将所有变量更改为私有实例变量,并在请求时使用函数更改它们的值。如果您需要使用脚本为多个玩家定义统计信息,则将其定义为静态将会导致问题。间接通过函数引用实例变量而不是直接调用变量名称也是常见做法。
public class PlayerInfo : MonoBehaviour {
    private string Name;
    private int Level;
    private int Health;
    private int Damage;
    private float moveSpeed;
    private float turnSpeed;

    public void SetHealth(int newHealthValue){
        Health += newHealthValue;
    }
    public void SetLevel(int newLevelValue){
        Level += newLevelValue;
    }
}

根据nate_moyer的回答,在碰撞函数中加入一个检查,以确定是否应执行该操作。
public class GiveHero : MonoBehaviour {
    private bool hasCollided = false;
    private void OnTriggerEnter(Collider other){
        if(!hasCollided){
            GetComponent<PlayerInfo>().SetHealth(-1); // Decrement the player's health by one.
            hasCollided = true;
        }
     }
}

或者如果你想销毁玩家触碰的对象:

    public class GiveHero : MonoBehaviour {
    private void OnTriggerEnter(Collider other){
        GetComponent<PlayerInfo>().SetHealth(-1); // Decrement the player's health by one.
        Destroy(other.gameObject); // Remove the Game Object the player collided with.
     }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接