I'm trying to make a character walk in unity but the error pops up that says "error CS1061: 'PlayerInput' does not contain a definition for 'CharacterControls' and no accessible extension method 'CharacterControls' accepting a first argument of type 'PlayerInput' could be found (are you missing a using directive or an assembly reference?)"
I can't seem to find anything that can help, plus I'm really new to C#, so please bear with me.
using UnityEngine;
using UnityEngine.InputSystem;
using System.Collections;
using System.Collections.Generic;
using static System.Numerics.Vector3;
class AnimationAndMovementController : MonoBehaviour
{
PlayerInput playerInput;
CharacterController characterController;
Animator animator;
Vector2 currentMovementInput;
Vector3 currentMovement;
bool isMovementPressed;
float rotationFactorPerFrame = 15.0f;
public bool IsMovementPressed { get => isMovementPressed; set => isMovementPressed = value; }
void Awake()
{
playerInput = new PlayerInput();
characterController = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
playerInput.CharacterControls.Move.started += onMovementInput;
playerInput.CharacterControls.Move.canceled += onMovementInput;
playerInput.CharacterControls.Move.performed += onMovementInput;
}
void handleRotation()
{
Vector3 posititonToLookAt;
posititonToLookAt.z = currentMovement.z;
posititonToLookAt.y = 0.0f;
posititonToLookAt.x = currentMovement.x;
Quaternion currentRotation = transform.rotation;
if (IsMovementPressed)
{
Quaternion targetRotation = Quaternion.LookRotation(posititonToLookAt);
transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, rotationFactorPerFrame * Time.deltaTime);
}
}
void onMovementInput (InputAction.CallbackContext context)
{
currentMovementInput = context.ReadValue<Vector2>();
currentMovement.x = currentMovementInput.x;
currentMovement.z = currentMovementInput.y;
IsMovementPressed = currentMovementInput.x != 0 || currentMovementInput.y != 0;
}
void handleAnimation()
{
bool isWalking = animator.GetBool("isWalking");
if (IsMovementPressed &
!isWalking)
{
animator.SetBool("isWalking", true);
}
else if (!IsMovementPressed & isWalking)
{
animator.SetBool("isWalking", false);
}
}
// Update is called once per frame
void Update()
{
handleRotation();
handleAnimation();
characterController.Move(currentMovement * Time.deltaTime);
}
void OnEnable()
{
playerInput.CharacterControls.Enable();
}
void OnDisable()
{
playerInput.CharacterControls.Disable();
}
}
any help is appreciated!
It looks like you were following a tutorial that was using the new "InputSystem". That means that your PlayerInput has been created for you, based on the details you used when creating your Input bindings. You have to go to your Actions window, which will look like ..
And from there, make sure that your action map is called exactly (spelling counts) "CharacterControls", and that it has a "Move" action, with as many move inputs as you want to include.
The fact that the IDE you are using (Microsoft Visual Studio?) didn't highlight this error before you even got back to the Unity editor makes me think your environment might not be set up correctly?
Related
I have a script to move my character(Player) in unity. The script is fine and it does not have any errors, Although when i enter
play mode and try to use the arrows to move my character, it does not move at all, i can't figure out what is the problem.
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 1f;
public float CollisionOffset = 0.05f;
public ContactFilter2D movementFilter;
Vector2 movementInput;
Rigidbody2D rb;
List<RaycastHit2D> castCollisions = new List<RaycastHit2D>();
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void FixedUpdate() {
if (movementInput != Vector2.zero) {
int count = rb.Cast(
movementInput,
movementFilter,
castCollisions,
moveSpeed * Time.fixedDeltaTime + CollisionOffset
);
if (count == 0) {
rb.MovePosition(rb.position + movementInput * moveSpeed * Time.fixedDeltaTime);
}
}
}
void onMove(InputValue movementValue) {
movementInput = movementValue.Get<Vector2>();
}
}
Unity version: 2022.2.0b14
Input System: version 1.2.0
Any help is appreciated.
OnMove not executing because it's OnMove not onMove. this is reference directly by new input system. So the Function name should be On+[ActionName] and here when you are using Default InputActions so Move -> OnMove.
I am trying to add particles to my Collison but I receive errors. I keep getting his error from my code and I don't know why. The errors are: OnGUIDepth changed: was 0 is 1. Event type was 0 (56,60): error CS1001: Identifier expected. (56,55): error CS1003: Syntax error, ',' expected
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController1 : MonoBehaviour
{
public float horizontalInput;
public float speed = 10.0f;
public float xRange = 100;
private Animator playerAnim;
public AudioClip crashSound;
private AudioSource playerAudio;
public GameObject projectilePrefab;
public ParticleSystem explosionParticle;
public bool isOnGround = true;
public bool gameOver;
// Start is called before the first frame update
void Start()
{
playerAudio = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update()
{
if (transform.position.x < -xRange)
{
transform.position = new Vector3(-xRange, transform.position.y, transform.position.z);
}
if (transform.position.x > xRange)
{
transform.position = new Vector3(xRange, transform.position.y, transform.position.z);
}
else
{
}
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * Time.deltaTime * speed);
if (Input.GetKeyDown(KeyCode.Space))
{
//Instantiate(projectilePrefab, transform.position, projectilePrefab.transform.rotation);
Instantiate(projectilePrefab, transform.position, transform.rotation);
}
}
private void OnCollisionEnter(Collision collision other)
{
if (other.gameObject.CampareTag("Rock"))
{
isOnGround = true;
} else if (other.gameObject.CompareTag("Star"))
{
Debug.Log("Game Over");
gameOver = true;
playerAnim.SetBool("Death_b", true);
playerAnim.SetInterger("DeathType_int", 1);
explosionParticle.Play();
playerAudio.PlayOneShot(crashSound, 1.0f);
}
}
}
Is there anything I need to fix in my code?
The errors here are already stated by the compiler and are an easy fix, just hover your mouse over and see what intellisense tells you
Let's go over this function
private void OnCollisionEnter(Collision collision other)
{
if (other.gameObject.CampareTag("Rock"))
{
isOnGround = true;
}
else if (other.gameObject.CompareTag("Star"))
{
Debug.Log("Game Over");
gameOver = true;
playerAnim.SetBool("Death_b", true);
playerAnim.SetInterger("DeathType_int", 1);
explosionParticle.Play();
playerAudio.PlayOneShot(crashSound, 1.0f);
}
}
In the first line, the
private void OnCollisionEnter(Collision collision other)
'other' makes no sense to be there. The Collision is the type, and collision is the identifier. People often put other as the identifier which you might have gotten confused. Seeing you are using other as the variable in the function, you can remove collision from the brackets.
The function further contains just spelling errors, such as .CampareTag which needs to be CompareTag
Please strictly follow syntax and use intellisense, it is an incredible tool which will 100% eliminate such errors.
The other error (if an error at all, seems like just a log)
OnGUIDepth changed: was 0 is 1. Event type was 0 (56,60):
is not contained within this script.
if (Input.GetKeyDown(KeyCode.Space))
{
if (jumpcheck = false)
{
bool jumpcheck = true;
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumppower, ForceMode2D.Impulse);
yield return new WaitForSeconds (2);
bool jumpcheck = false;
}
The bool is the variable named "jumpcheck" What was supposed to happen was, if the space key is pressed, check if the variable jumpcheck is false, if it is false, set jumpcheck to true, execute the jump command, then set the jumpcheck variable back to false after 2 seconds.
Here is all of the code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class jeff : MonoBehaviour
{
public float movespeed = 5f;
public float jumppower = 10f;
// Start is called before the first frame update
void Start()
{
bool jumpcheck = false;
}
// Update is called once per frame
void Update()
{
StartCoroutine(Test ());
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * movespeed;
}
IEnumerator Test ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (jumpcheck = false)
{
bool jumpcheck = true;
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumppower, ForceMode2D.Impulse);
yield return new WaitForSeconds (2);
bool jumpcheck = false;
}
}
}
}
I am getting multiple errors
Assets/jeff.cs(34,15): error CS1525: Invalid expression term 'bool'
Assets/jeff.cs(34,20): error CS1026: ) expected
Assets/jeff.cs(34,37): error CS1002: ; expected
Assets/jeff.cs(34,37): error CS1513: } expected
You should make your code more like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class jeff : MonoBehaviour
{
public float movespeed = 5f;
public float jumppower = 10f;
bool jumpcheck;
// Start is called before the first frame update
void Start()
{
jumpcheck = false;
}
// Update is called once per frame
void Update()
{
StartCoroutine(Test ());
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * movespeed;
}
IEnumerator Test ()
{
if (Input.GetKeyDown(KeyCode.Space))
{
if (jumpcheck == false)
{
jumpcheck = true;
gameObject.GetComponent<Rigidbody2D>().AddForce(Vector3.up * jumppower, ForceMode2D.Impulse);
yield return new WaitForSeconds (2);
jumpcheck = false;
}
}
}
}
Hello and congrats your first question on StackOverflow. I think your game code logic need some improvement also I edited your code so that it won't go on any compiler error
You was declaring jumpcheck bool variable every time you was using it in the same scope(which is error), what you needed was one declaration on a class level and declaration time assignment with value
In C# when comparing two values with each other we use == operator for that, and = for value assignments(see more about comparison operators here
Also I modified your code so that your logic should be same but more likely bug free, Coroutines are not consistent with Update and if you are running Coroutine every frame in update you will likely end up with performance issues. So I rewrote code such that Coroutine only handles timing so it will be called only after 2 seconds at the worst case
And finally I humbly ask you to follow common C# naming convention, I modified some variable names and also class name from lowerCase jeff to PasCalCase Jeff.
So here is C# naming conventions
And finally here is the code with all mentioned applied
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Jeff : MonoBehaviour
{
public float movespeed = 5f;
public float jumppower = 10f;
private bool jumpCheck = false;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && !jumpCheck)
{
gameObject.GetComponent<Rigidbody2D>()
.AddForce(Vector3.up * jumppower, ForceMode2D.Impulse);
jumpCheck = true;
StartCoroutine(ResetJumpCheck());
}
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position += movement * Time.deltaTime * movespeed;
}
IEnumerator ResetJumpCheck()
{
yield return new WaitForSeconds(2);
jumpCheck = false;
}
}
First of all as per your implementation, this is of no use, because it local to Start method.
void Start()
{
bool jumpcheck = false;
}
And compilation error is due to this line, there has to be == not = in if condition
if (jumpcheck = false) //wrong
H, I'm going to develop a drag and drop game with unity but this error appears, how to fix this error, please!
this is the full error
( error CS1061: 'GameObject' does not contain a definition for 'localPosition' and no accessible extension method 'localPosition' accepting a first argument of type 'GameObject' could be found (are you missing a using directive or an assembly reference?))
this is my code in the C# script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveSystem : MonoBehaviour
{
public GameObject correctForm;
private bool moving; // to check if it is moving or not
private float startPosX;
private float startPosY;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(moving){
Vector3 mousePos;
mousePos= Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.gameObject.localPosition.z);
}
}
public void OnMouseUp(){
moving = false;
}
public void OnMouseDown(){
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
startPosX = mousePos.x - this.transform.localPosition.x;
startPosY = mousePos.y - this.transform.localPosition.y;
moving = true;
}
}
}
In the update function, in last parameter of last line, you typed this.gameObject.localPosition.z. GameObject has no field named localPosition. You should fix it by this.gameObject.transform.localPosition.z. In conclusion, your Update should looks like this:
// Update is called once per frame
void Update()
{
if(moving){
Vector3 mousePos;
mousePos= Input.mousePosition;
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
this.gameObject.transform.localPosition = new Vector3(mousePos.x - startPosX, mousePos.y - startPosY, this.gameObject.transform.localPosition.z);
}
}
I work on a game. A part is offline and the other one using network.
I've create a copy of my script to work offline. There is no error on my script (monobehaviour) but when I tried to add the component on my GameObject unity throw me an error :
"Can't add script component 'RocketOffline' because the script class
cannot be found. Make sure that there are no compile errors and that
the file name and class name match"
I don't see any error in my script and names match (RocketOffline.cs VS RocketOffline : MonoBehaviour)
I've tried to re-import my script, re-import all assets and copy all of my code in another script but nothing seem to works...
I've same problem on other script but I'll only show one of them
public class RocketOffline : MonoBehaviour
{
public GameObject Explosion;
private Vector3 Direction;
private Color Couleur;
private float vitesse;
private float multiplieur;
int NumPlayer;
void Explose(Vector3 position)
{
ExplosionOffline instance = Instantiate(Explosion, position, new Quaternion()).GetComponent<ExplosionOffline>();
instance.NumPlayer = NumPlayer;
foreach (var SmokeEffect in GetComponentsInChildren<ParticleSystem>())
{
SmokeEffect.transform.parent = null;
Destroy(SmokeEffect.gameObject, SmokeEffect.startLifetime);
SmokeEffect.Stop();
}
Destroy(gameObject);
}
private void OnCollisionEnter(Collision collision)
{
Explose(transform.position);
}
private void OnTriggerExit(Collider other)
{
GetComponent<Collider>().isTrigger = false;
}
public void SetSpeed(Vector3 _Direction, float _Vitesse, JoueurOffline _Player)
{
Direction = _Direction;
vitesse = _Vitesse;
Couleur = _Player.Couleur;
NumPlayer = _Player.NumPlayer;
}
void Start()
{
Rigidbody rigid = GetComponent<Rigidbody>();
transform.eulerAngles = Vector3.forward * Mathf.Atan2(-Direction.x, Direction.y) * Mathf.Rad2Deg;
rigid.velocity = Direction * vitesse;
multiplieur = transform.localScale.y / 10;
GetComponentInChildren<MeshRenderer>().material.color = Couleur;
}
void Update()
{
GetComponent<Rigidbody>().velocity = transform.up * vitesse;
RaycastHit info;
Physics.Raycast(new Ray(transform.position, GetComponent<Rigidbody>().velocity * Time.deltaTime), out info);
if (info.distance < vitesse * Time.deltaTime * multiplieur/* && info.collider.gameObject != gameObject && info.collider.gameObject != player.gameObject*/)
{
Explose(info.point);
}
}
}
I only want to add my script on my GameObject like usually on Unity.
But there is always the same error.
My script was tested on other project and work perfectly. I think it's probably an internal bug of unity.
Yep, this is potentially a bug of Unity.
If you're using the new 2019 beta, then just do a Bug Report :)
i think you can try to reimport the script or rm the library folder of your project.