Changing player position on start based on the position values of a randomly selected cube from a list

Hello,

I have a series of cubes placed in my level and I want to randomly select one of them, and transform the position of the player according to the position values on the selected “spawn” object, on start. I’m new to programming as a whole, so I’m not quite sure what detail I am missing for this to occur.

  public GameObject player;
  public GameObject[] spawnspots;
  private Vector3 spawnLocation;
  private Vector3 PlayerStart;
  void Awake()
  {
      player = GameObject.Find("Player");
      PlayerStart = player.transform.position;
      spawnspots = GameObject.FindGameObjectsWithTag("Respawn");
  }
  void Start()
  {
      setspawnlocation();
  }
  void setspawnlocation()
  {
      int spawn = Random.Range(0, spawnspots.Length);
      spawnLocation = spawnspots[spawn].transform.position;
      PlayerStart = spawnLocation;
  }

This doesn’t look to bad, I think the only thing you are missing is to actually use your cube location to move the player to your desired spot. Add this to the end of your setspawnlocation function.

player.transform.position = spawnLocation;

I think where you are getting mixed up is you think that by setting PlayerStart = player.transform.position; in your Awake method, you can now treat PlayerStart as player.transform.position, just under a different name. This is not the case. When you call PlayerStart = player.transform.position, PlayerStart just gets a copy of whatever value player.transform.position has. If the player position was (1,1,1), PlayerStart is now (1,1,1). But if the player position changes, PlayerStart keeps its value of (1,1,1).
**
So when you say PlayerStart = spawnLocation; you are not changing the position of the player, you are just saying “Ok, PlayerStart had some Vector3 value that was at one point copied from the player position, but now I want it to forget that value and copy from spawnLocation instead”.
**
If this is still confusing I recommend looking up the difference between “pass by reference” and “pass by value”. Since Vector3 is a struct it always copies its data, rather than holding a reference to the original data.