C#和Unity:通过值传递引用? [英] C# & Unity : Pass reference by value?

查看:256
本文介绍了C#和Unity:通过值传递引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#和Unity的新手,在这里我进行调整并创建了我的第一个迷你游戏.

I'm new to C# and Unity, and here I am tweaking and creating my first minigame.

这是问题所在:
我有一个小方块,可以移动.我已经实现了一种在移动之前检查下一个位置的方法. 该方法接收当前立方体位置和方向作为参数:

Here is the problem:
I've got a little cube, that moves. I've implemented a method that checks the next position before making a move. The method receives as parameters the current cube position, and the direction:

 public bool okToMove(Transform playerCurrentPosition , int directionIndex)
{
   Transform playerNextPosition = playerCurrentPosition;

   playerNextPosition.Translate(toDirection(directionIndex));

    if (playerNextPosition.position.x > 1 ||
        playerNextPosition.position.x < -1 ||
        playerNextPosition.position.y > 1 ||
        playerNextPosition.position.y < -1)
        return false;
    else
        return true;
    }

然后,我调用该方法

public void movePlayer(int directionIndex)
{
    if (  okToMove(gameObject.transform, directionIndex) )
        transform.Translate(toDirection(directionIndex));

}

问题在于多维数据集一次执行2次移动.这是因为

The problem is that the cube makes 2 moves at once. This is because of

transform.Translate(toDirection(directionIndex));

playerNextPosition.Translate(toDirection(directionIndex));

okToMove方法调用的

. Unity或C#将playerNextPosition视为实际的多维数据集,而不是仅存在于方法内部的某种临时副本.

that is called from okToMove method. Unity or C# sees playerNextPosition as the real cube, and not somekind of temporary copy that only exists inside the method.

那么为什么我的gameObject.transform作为参考而不是按值传递?我该如何运作?

So why is my gameObject.transform being passed as a reference and not by value? How can I make it work?

在此先感谢您的配合.

推荐答案

您正在传递对Transform的引用,然后在"okToMove"中使用translate将其移动,最好的方法是制作Vector3的副本,只需更改您的"okToMove"像这样.

You are passing reference to Transform and then moving it with translate in "okToMove", best way is to make a copy of Vector3, just change your "okToMove" like this.

public bool okToMove(Transform playerCurrentPosition , int directionIndex){
    Vector3 playerNextPosition = playerCurrentPosition.position;

    playerNextPosition += toDirection(directionIndex);

    if (playerNextPosition.x > 1 ||
        playerNextPosition.x < -1 ||
        playerNextPosition..y > 1 ||
        playerNextPosition.position.y < -1)
        return false;
    else
    return true;
}

Transform是连接到每个gameObject的组件,并且它包含位置,旋转和比例的值,因此您的"playerCurrentPosition"不是位置的副本,而是对Transform的引用(不是副本).

Transform is component attached to each gameObject and it holds values for position, rotation and scale, so your "playerCurrentPosition" is not copy of position but rather reference to Transform (not a copy).

这篇关于C#和Unity:通过值传递引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆