I'm making a game where the player is a square and it changes shape when he presses a key. To do that I made different prefabs because I have different things to change. When I press the key to change to one prefab, I set active the corresponding prefab and I disable the other. The problem is here, I have three prefabs and I don't know where to connect to change the position runtime. I tried to make the position equal to the others but it didn't work.
Here there is the code I made:
public class Transformation : MonoBehaviour
{
public GameObject normal, small, big;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("q"))
{
big.SetActive(true);
normal.SetActive(false);
small.SetActive(false);
big.transform.position = normal.transform.position = small.transform.position;
}
if (Input.GetKeyDown("w"))
{
normal.SetActive(true);
big.SetActive(false);
small.SetActive(false);
normal.transform.position = big.transform.position = small.transform.position;
}
if (Input.GetKeyDown("e"))
{
small.SetActive(true);
normal.SetActive(false);
big.SetActive(false);
small.transform.position = big.transform.position = normal.transform.position;
}
}
}
CodePudding user response:
Make one empty GameObject
and apply all movement logic to it. Put normal, small and big objects as children of the main GameObject
and just enable/disable them as you need.
CodePudding user response:
If you want the location of these gameObjects to be moved to the location of the script object. It is better to try this:
void Update()
{
small.SetActive(false);
normal.SetActive(false);
big.SetActive(false);
if (Input.GetKeyDown("q"))
{
big.SetActive(true);
big.transform.position = transform.position;
}
else if (Input.GetKeyDown("w"))
{
normal.SetActive(true);
normal.transform.position = transform.position;
}
else if (Input.GetKeyDown("e"))
{
small.SetActive(true);
small.transform.position = transform.position;
}
}