问题描述
我的项目有一个奇怪的问题,我试图通过按一个键在 2 个游戏对象 -village 和狼人之间切换(两者都是同一个空游戏对象的孩子)。出于某种原因,它只切换了一次并“卡在”狼人游戏对象上,而没有切换回村民。这是我第二次尝试处理 getter/setter。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class WerewolfTransform : MonoBehavIoUr
{
public GameObject villager;
public GameObject wereWolf;
public bool isWerewolf;
private void Awake()
{
villager.SetActive(true);
wereWolf.SetActive(false);
}
public bool getIsWereWolf
{
set
{
if (isWerewolf != value)
{
isWerewolf = value;
villager.SetActive(false);
wereWolf.SetActive(true);
}
else
{
villager.SetActive(true);
wereWolf.SetActive(false);
}
}
get
{
return isWerewolf;
}
}
private void Update()
{
Transformation();
}
public void Transformation()
{
if (Input.GetKeyDown(KeyCode.T))
{
wereWolf.transform.position = villager.transform.position;
getIsWereWolf = !getIsWereWolf;
}
}
}
解决方法
好吧,每当您更改值时,第一个案例就会启动并且您很难设置
villager.SetActive(false);
wereWolf.SetActive(true);
无论您实际将其更改为什么值。
你宁愿这样做,例如
public bool getIsWereWolf
{
set
{
isWerewolf = value;
villager.SetActive(!isWerewolf);
wereWolf.SetActive(isWerewolf);
}
get => isWerewolf;
}
为了确保初始状态一致,我还会在 Awake
private void Awake()
{
getIsWerewolf = false;
}
,
首先感谢! 我做了一些与你建议的非常相似的事情,它奏效了! 我发布了我所做的事情(布尔没有像我想要的那样工作,我去了另一个方向)
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class WerewolfTransform : MonoBehaviour
{
public GameObject villager;
public GameObject wereWolf;
//public bool isWerewolf;
public int formSwitch;
private void Awake()
{
villager.SetActive(true);
wereWolf.SetActive(false);
formSwitch = 1;
}
private void Update()
{
Transformation();
}
public void Transformation()
{
if (Input.GetKeyDown(KeyCode.T) && formSwitch == 1)
{
villager.SetActive(false);
wereWolf.SetActive(true);
formSwitch = 2;
wereWolf.transform.position = villager.transform.position;
wereWolf.transform.rotation = villager.transform.rotation;
}
else if (Input.GetKeyDown(KeyCode.T) && formSwitch == 2)
{
villager.SetActive(true);
wereWolf.SetActive(false);
formSwitch = 1;
villager.transform.position = wereWolf.transform.position;
villager.transform.rotation = wereWolf.transform.rotation;
}
}
}