我有很多函数基本上使用不同的变量工作。简短的例子:
[SyncVar] private Vector3 syncedPlayerPosition;
[SyncVar] private Vector3 syncedHandPosition;
private Transform playerTransform;
private Transform handTransform;
private float lerpPlayerPositionRate;
private float lerpHandPositionRate;
void SetPlayerPosition(){
if(playerTransform.position != syncedPlayerPosition){
playerTransform.position = Vector3.Lerp(playerTransform.position, syncedPlayerPosition, Time.deltaTime * lerpPlayerPositionRate);
}
}
void SetHandPosition(){
if(handTransform.position != syncedHandPosition){
handTransform.position = Vector3.Lerp(handTransform.position, syncedHandPosition, Time.deltaTime * lerpHandPositionRate);
}
}
正如你所看到的,两个函数基本上完全相同,只是使用不同的变量。
现在我正在寻找类似的东西(假设Dictionary
会像那样工作)
[SyncVar] private Vector3 syncedPlayerPosition;
[SyncVar] private Vector3 syncedHandPosition;
private Transform playerTransform;
private Transform handTransform;
private float lerpPlayerPositionRate;
private float lerpHandPositionRate;
/* Add Dictionaries to reference those variables */
private Dictionary<Transform,Vector3> positionDict = new Dictionary<Transform,Vector3>();
private Dictionary<Transform,float> lerpRateDict = new Dictionary<Transform,float>();
private void Start(){
/* Fill the Dictionaries with Links between the Transforms
* to the achording variable reference */
/* Until now not the references are linked but rather values written */
positionDict.Add(playerTransform, syncedPlayerPosition);
positionDict.Add(handTransform, syncedHandPosition);
lerpRateDict.Add(playerTransform, lerpPlayerPositionRate);
lerpRateDict.Add(handTransform, lerpHandPositionRate);
}
/* Than I could use (and change) only one common function for both e.g like */
void SetPosition(Transform transform){
if(transform.position != positionDict[transform]){
transform.position = Vector3.Lerp(transform.position, positionDict[transform], Time.deltaTime * lerpRateDict[transform]);
}
/* Add this only as example that also this has to be posible */
lerpRateDict[transform] += 1;
positionDict[transform] = Vector3.zero();
}
我实际上是通过这种方式尝试过的,但我意识到Dictionary
中的值不会更新,但在调用Start()
时会保留其中的任何内容。因此,在我看来,它们并未Dictionary
添加到Reference
,而是添加Value
。
是否可以以某种方式设置它,以便在字典中实际上不存储值,而是存储对现有变量的引用?我怎么能达到这样的目的呢?
我确实有很多这些功能,每一个小小的改变都必须逐一应用。像我正在寻找的设置将允许我只对所有人进行一次更改。
修改
我忘了提到:在这些函数中,有时候Vector3
和float
值也可能会更改Transform
s。
答案 0 :(得分:4)
为什么不创建一个可以为所有变换调用的方法:
void SyncPositions(Transform thisTransform, Vector3 targetPosion, float rate)
{
if (thisTransform.position != targetPosion)
{
thisTransform.position = Vector3.Lerp(thisTransform.position, targetPosion, Time.deltaTime * rate);
}
}
您可以将其称为播放器变换或手动变换。
SyncPosition(playerTransform,syncedPlayerPosition,lerpPlayerPositionRate);
SyncPosition(handTransform,syncedHandPosition,lerpHandPositionRate);
希望这会有所帮助