error CS1061: Type `UnityEngine.Component' does not contain a definition for `position' and no extension method `position' of type `UnityEngine.Component' could be found.
I get this error when trying to compile the PlayerController script for the Space Shooter tutorial. I have tried looking around but as far as I can tell my code is identical to the one in the tutorial (with the exception of the GetComponent() for the updated version. My code looks like this:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class PlayerController : MonoBehaviour { public float speed; public float xMin, xMax, zMin, zMax; void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
GetComponent<Rigidbody>().velocity = movement * speed;
GetComponent<Rigidbody>().position = new Vector3
(
Mathf.Clamp(rigidbody.position.x, xMin, xMax),
0.0f,
Mathf.Clamp(rigidbody.position.z, zMin, zMax)
);
}
}
Answer by Jawchewa · Jun 14, 2017 at 04:36 AM
The problem is on the lines where you are doing this:
Mathf.Clamp(rigidbody.position.x, xMin, xMax),
Calling rigidbody on a component like that was kind of the old Unity way of doing things, and doesn't work anymore. To make it work you would have to change it to
Mathf.Clamp(GetComponent<Rigidbody>().position.x, xMin, xMax),
But what I would probably recommend it to cache the rigidbody, so you don't have to call get GetComponent a ton of times. So, store the rigidbody like this:
Rigidbody rigidbody = GetComponent<Rigidbody>();
And use that instead.
Your answer
![](https://koobas.hobune.stream/wayback/20220612124132im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Script problem: Trying to make the code of this script run at a set interval (GUI handle object) 1 Answer
Dreamlo Leaderbord issue 0 Answers
HELP ! Highscore name input after each Death 0 Answers
How to get variables of a behavior tree with RAIN AI 0 Answers
Having trouble deleting objects from a list after they reach a certain scale. 0 Answers