Home > Enterprise >  Set position for player from variable in Unity
Set position for player from variable in Unity

Time:11-01

Me need set random position in Start() for player as minecraft.

Player already have the script, but position don't change of default.

Error in 24 and 25 string.

Code:


using UnityEngine;

public class RandomRespawn : MonoBehaviour
{
    [Header("Игрок")] // player
    public GameObject Player;

    [Header("Объявление координат")] // have position
    public int positionX;
    public int positionZ;

    [Header("Рандомные координаты")] // random position
    public int randomPosX;
    public int randomPosZ;

    private void Start()
    {
        System.Random randomPos = new System.Random();
        Vector3 positions = transform.position;

        positionX = randomPos.Next(1, 50);
        positionZ = randomPos.Next(1, 50);

        gameObject.positions.x = positionX;
        gameObject.positions.z = positionZ;
    }
}

I have error: (25,20): error CS1061: 'GameObject' does not contain a definition for 'positions' and no accessible extension method 'positions' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?), now =(

CodePudding user response:

To change the position of the attached player gameobject, you need to change this:

gameObject.positions.x = positionX;
gameObject.positions.z = positionZ;

To this:

Player.transform.position = new Vector3(positionX, positionZ, Player.transform.position.z);

CodePudding user response:

You can't get the position properties from GameObject, you need to get the position from Transform properties.

And you can't directly set the value of position.x directly from a float value. You must create a new Vector3 variable and set the value first. And then you can apply that variable value to your transform.position.

  • Related