Reputation: 11
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.
Upvotes: -1
Views: 1496
Reputation: 11
You can't access transform.position.x directly because it belongs to position's Vector3 struct. I encourage you to better understand C# structs
float x;
float y;
float z;
void Move()
{
// THIS WORKS
transform.position = new Vector3(x,y,z);
// THIS DOESN'T WORK
transform.position = 23f;
transform.position.x = 10f;
}
Upvotes: 0
Reputation: 590
if you want to change only a single axis in transfrom.position
, then you need to use a temp Vector2. Here is how to do it:
Vector2 temp_pos=transform.position;
temp_pos.x=player.transform.position.x + offset
transform.position=temp_pos;
If You want to update the position directly, then you can just do this:
transform.position = new Vector2(player.transform.position.x + offset, transform.position.y);
Upvotes: 0
Reputation: 321
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;
Upvotes: 1
Reputation: 101
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
Upvotes: 0