Reputation: 41
I've got weird issue with my project, I'm trying to change between 2 gameobjects -villager to werewolf (both are children of the same empty gameobject) by pressing a key. for some reason it switching only one time and "stuck" at werewolf gameobject without switching back to villager. it's the second time I'm trying to handle the 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;
}
}
}
Upvotes: 0
Views: 925
Reputation: 41
First of all thanks! And I did something very similar to what u have suggested and it worked! Ill posted what I've done ( the bool didnt worked as i wanted to I went for another direction)
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;
}
}
}
Upvotes: 0
Reputation: 90679
Well whenever you change the value the first case kicks in and you hard set
villager.SetActive(false);
wereWolf.SetActive(true);
no matter what value you are actually changing it to.
You would rather do it like e.g.
public bool getIsWereWolf
{
set
{
isWerewolf = value;
villager.SetActive(!isWerewolf);
wereWolf.SetActive(isWerewolf);
}
get => isWerewolf;
}
To be sure to have a consistent initial state I would then also use it in Awake
private void Awake()
{
getIsWerewolf = false;
}
Upvotes: 1