Home > Software design >  How can you add a variable to a position in unity 2D?
How can you add a variable to a position in unity 2D?

Time:06-27

I need help, I am coding an boss AI and I can't seem to add a variable to a position in unity.

Here is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FistScript : MonoBehaviour
{
    public GameObject player;
    public float offset;
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        transform.position.x = new Vector2(player.transform.position.x   offset, transform.position.y);
    }
}

When I use this I get this error:

'Assets\Scripts\FistScript.cs(18,9): error CS1612: Cannot modify the return value of 'Transform.position' because it is not a variable'

Please help if you can.

CodePudding user response:

In order to update position you can update transform.position, not the transform.position.x i.e

//update the position
    transform.position = transform.position   new Vector3(horizontalInput * movementSpeed * Time.deltaTime, verticalInput * movementSpeed * Time.deltaTime, 0);

For more information please refer to https://docs.unity3d.com/ScriptReference/Transform-position.html

CodePudding user response:

You're trying to assign Vector2 to float property. transform.position is a Vector2 struct with properties x and y. So you can't modify them because they are properties of a struct. To modify the position you should create a new Vector2 object.

player.transform.position = new Vector2(player.transform.position.x   offset, player.transform.position.y);

Simpler variant:

player.transform.position  = Vector2.right * offset;
  • Related