This is my full script
I get an error on line 15, beginning at the "PlayerControls" word.
error CS0246: The type or namespace name 'PlayerControls' could not be found (are you missing a using directive or an assembly reference?)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace puggy
{
public class InputHandler : MonoBehaviour
{
public float horizontal;
public float vertical;
public float moveAmount;
public float mouseX;
public float mouseY;
PlayerControls inputActions;
Vector2 movementInput;
Vector2 cameraInput;
public void OnEnable()
{
if (inputActions == null)
{
inputActions = new PlayerControls();
inputActions.PlayerMovement.Movement.performed += inputActions => movementInput = inputActions.ReadValue<Vector2>();
inputActions.PlayerMovement.Camera.performed += i => cameraInput = i.ReadValue<Vector2>();
}
inputActions.Enable();
}
private void OnDisable()
{
inputActions.Disable();
}
public void TickInput(float delta)
{
MoveInput(delta);
}
private void MoveInput(float delta)
{
horizontal = movementInput.x;
vertical = movementInput.y;
moveAmount = Mathf.Clamp01(Mathf.Abs(horizontal) + Mathf.Abs(vertical));
mouseX = cameraInput.x;
mouseY = cameraInput.y;
}
}
}
I'm guessing it wants a reference for "PlayerControls". I'm confused though because I followed a walkthrough, I ran into other issues but was able to resolve them pretty quickly. This one is tripping me up though.
I'm expecting to be able to attach this script to my player model and have it move based on player input.
I have re-typed my script and followed other forums to see if anyone else has had similar issues.
EDIT:
public class PlayerControls has to be in a file called PlayerControls.cs!
Looking at your screenshot you have InputHandler in a file called PlayerControls.cs
I guess you copied/renamed the class or file. Please make sure Filename and Classname match!
I figured it out. When making the "PlayerControls Input Action" I forgot to also click "generate C# class".
This makes sure that all the stuff I set up in the GUI, is applied into the C# script.
Related
Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class PointSystem : MonoBehaviour
{
public Rigidbody2D rb1;
public Rigidbody2D rb2;
public TextMeshProUGUI plr1T;
public TextMeshProUGUI plr2T;
public float UIVal1 = 1f;
void Start()
{
plr1T = FindObjectOfType<TextMeshProUGUI>();
plr2T = FindObjectOfType<TextMeshProUGUI>();
}
void OnCollisionEnter2D(Collision2D other)
{
if (other.gameObject.tag == "PlayerAI")
{
UpdateUI();
}
}
void UpdateUI()
{
plr1T.text = (UIVal1.ToString());
UpdateFloat();
}
void UpdateFloat()
{
UIVal1 = +1f;
}
}
I want to change the UI text once they collide with an object and increase the value so if they hit it again the number in the text increases. It also does not show any errors. Please help.
I have tried using the ToString() method but it still does not change the text.
I see few minor errors from your code:
FindObjectOfType returns the first active loaded object that matches the specified type. It returns null if no Object matches the type. Since you have your plr1T and plr2T set in public, you can just assign them in the inspector. If you do that, you can remove the codes from your Start() method. Check the documentation here:
https://docs.unity3d.com/ScriptReference/Object.FindObjectOfType.html
This is not really an error, but a best practice. After checking for tags, you can do a null check to avoid Exception error.
You can do:
if(other.gameObect != null)
Before calling this code:
UpdateUI();
If you're incrementing by 1, you can do: UIVal1++, or UIVal1 += 1.
You made a mistake when incrementing the UIVAL1,
the is the right way :
void UpdateFloat()
{
UIVal1 = UIVal1 +1;
}
Just picked up Unity about a week ago, I have really been struggling to fix this problem and referencing overall, I'm well aware that I need to read and watch more tutorials, I just want to get this fixed so I can continue working on my game.
An object reference is required for the non-static field, method, or property PlayerMovement.activeMoveSpeed
The first problem was referencing the other Game Object and script, I not sure if its completely fixed now but
at least that not the error that its giving me anymore, I've tried doing what this link says
https://answers.unity.com/questions/1119537/help-how-do-i-referenceaccess-another-script-in-un.html
but as you might see it hasn't worked out, every single time I get the compile errors fixed the script doesn't work because the object reference is not set to an instance of an object, any help would be extremely appreciated (the script I'm trying to reference will be at the end)
Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ShieldAttack : MonoBehaviour
{
public GameObject shield;
private Vector3 mousePos;
private Camera mainCam;
public bool isDashing;
private Rigidbody2D rb;
GameObject Player;
PlayerMovement playerMovement;
Shooting shooting;
// Start is called before the first frame update
void Start()
{
GameObject.FindGameObjectWithTag("EnemyMelee");
GameObject.FindGameObjectWithTag("Enemy2");
mainCam = GameObject.FindGameObjectWithTag("MainCamera").GetComponent<Camera>();
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
mousePos = mainCam.ScreenToWorldPoint(Input.mousePosition);
Vector3 rotation = mousePos - transform.position;
float rotZ = Mathf.Atan2(rotation.y, rotation.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, rotZ);
if (Input.GetKeyDown(KeyCode.Space) && playerMovement.dashCoolCounter <= 0 && playerMovement.dashCounter <= 0)
{
isDashing = true;
Instantiate(shield, shooting.bulletTransform.position, Quaternion.identity);
if (PlayerMovement.activeMoveSpeed == 5)
{
DestroyShield();
isDashing = false;
}
}
}
void DestroyShield()
{
Destroy(gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed;
public Rigidbody2D rb2d;
private Vector2 moveInput;
public float activeMoveSpeed;
public float dashSpeed;
public float dashLength = 0.5f, dashCooldown = 1f;
public float dashCounter;
public float dashCoolCounter;
[SerializeField] private TrailRenderer tr;
//Start is called before the first frame update
void Start()
{
activeMoveSpeed = moveSpeed;
}
//Update is called once per frame
void Update()
{
if(dashCounter > 0)
{
tr.emitting = true;
}
if(dashCounter < 0)
{
tr.emitting = false;
}
moveInput.x = Input.GetAxisRaw("Horizontal");
moveInput.y = Input.GetAxisRaw("Vertical");
moveInput.Normalize();
rb2d.velocity = moveInput * activeMoveSpeed;
if (Input.GetKeyDown(KeyCode.Space))
{
if (dashCoolCounter <=0 && dashCounter <=0)
{
activeMoveSpeed = dashSpeed;
dashCounter = dashLength;
}
}
if (dashCounter > 0)
{
dashCounter -= Time.deltaTime;
if (dashCounter <= 0)
{
activeMoveSpeed = moveSpeed;
dashCoolCounter = dashCooldown;
}
}
if (dashCoolCounter > 0)
{
dashCoolCounter -= Time.deltaTime;
}
}
}
You are using class name PlayerMovement.activeMoveSpeed instead of object name playerMovement.activeMoveSpeed in this part of code:
if (PlayerMovement.activeMoveSpeed == 5)
{
DestroyShield();
isDashing = false;
}
Also I cannot see playerMovement variable initialization in the ShieldAttack script. You need to mark it with the [SerializeField] attribute or make it public to be able to assign it in the inspector. Or initialize it in your Start() method along with the other fields.
When you create a variable, you do <type> <name>, where <type> is the kind of thing you want to create and <name> is how you want to reference the instance you created.
We as programmers are generally lazy, so if we wanted to create a pineapple we would create an instance of the Pineapple class. What do we call it? Typically just pineapple, and then you wind up with code like
Pineapple pineapple;
The first term means you're wanting to create a Pineapple, and the second term means you're going to refer to that instance as pineapple. Note the capitalization differences there.
The issue with your code is that you've created an instance of PlayerMovement:
PlayerMovement playerMovement;
but when you're trying to use the instance in your code, you are using the class name PlayerMovement and not the instance name playerMovement. Again, note the capitalization difference.
The particular line that you've got:
if (PlayerMovement.activeMoveSpeed == 5)
should instead be:
if (playerMovement.activeMoveSpeed == 5)
to refer to the instance and not the class.
It is possible to have things that are common to all instances of a class. Those are static items and you would access them by referencing the class name instead of the instance name.
The error message you got:
An object reference is required for the non-static field, method, or property PlayerMovement.activeMoveSpeed
was telling you that you were trying to access a part of the class, but it wasn't static, so you needed to reference the object (instance).
im trying to grab the transform component via t.find and then via the transform component, grab the game object component, and then t.LookAt can work, and look at the player.
this is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class gunner : MonoBehaviour
{
//legacy statements: isShot
//these statements initialize all the main variables used in the project. most of these are for the "ai".
#region variables
[Header("gun stats")]
[Space(10)]
public float damage = 10f;
public float range = 100f;
[Space(10)]
[Header("Camera")]
[Space(10)]
public Camera cam;
[Space(10)]
[Header("AI Variables")]
[Space(10)]
public float shootlength;
public bool aiactive;
public float Speed;
public target self;
public Transform t;
public Rigidbody rb;
public string playername = "Player";
public GameObject PlayerObject;
public Transform PlayerTrans;
[Header("Decor")]
public ParticleSystem ps;
AudioSource audioData;
#endregion
#region gunmanager
private void Start()
{
GameObject PlayerObject = GameObject.Find(playername);
Transform PlayerTrans = PlayerObject.GetComponent<Transform>();
}
void Update()
{
if(aiactive && PlayerTrans != null)
{
Debug.Log("player trans found!");
}
if(aiactive && PlayerObject != null)
{
Debug.Log("player gameObject found!");
}
if(aiactive && PlayerTrans != null && PlayerObject != null)
{
Debug.Log("test passed!");
}
audioData = GetComponent<AudioSource>();
if (Input.GetButtonDown("Fire1") && !aiactive)
{
audioData.Play(0);
Shoot();
}
if(aiactive)
{
StartCoroutine(aiman());
}
}
public void Shoot()
{
ps.Play();
RaycastHit hit;
if(Physics.Raycast(cam.transform.position, cam.transform.forward, out hit, range))
{
Debug.Log("Hit:" + hit.transform.name);
target targ = hit.transform.GetComponent<target>();
if (targ != null)
{
if(!aiactive)
{
self.hp += 50;
}
targ.TakeDamage(damage);
}
}
}
public void aiActivity()
{
if(self.hp >= 0)
{
t.LookAt(PlayerTrans);
rb.AddRelativeForce(Vector3.forward * Speed * Time.deltaTime);
RaycastHit hitplayer;
if(Physics.Raycast(cam.transform.position, cam.transform.forward, out hitplayer, shootlength))
{
if(hitplayer.transform == PlayerObject)
{
Shoot();
}
}
}
else
{
rb.useGravity = true;
aiactive = false;
}
}
IEnumerator aiman()
{
yield return new WaitForSeconds(1f);
aiActivity();
}
#endregion
}
so no compiler errors, but it cannot find the player and float towards it, and therefore, I cannot get this to work.
Here are a few issues with the updated snippet, not sure if they will fix all of the errors you are getting.
You are re-using a variable name t. I would also refrain from naming any global variables very short random letters as it can get confusing. What is this a Transform of? If it is the transform of a player, possibly name it PlayerTransfom.
As I mentioned you are re-using a variable name which is not allowed especially with different types as well as re-initilization. It is fine to re-assign a variable such that it is updated, manipulating, changing, etc. the value, but re-declaring the value is not allowed in c# and I do not believe allowed in any other language (at least that I know of).
To be specific, the line target t = hit.transform.GetComponent<target>(); is delcaring t as the script component type target, but you have already declared a Transform named t above it as public Transform t;.
Another issue is you are attempting to assign a variable using a non-static method in a global setting. The line specifically is public Transform player = Transform.Find(playername);. You are not able to set the transform like this outside of a method as the Find method is not static. Change it to be.
public Transform player;
private void Start()
{
player = Transform.Find(playername);
}
The second error is because of the same reason, but due to this line public GameObject PlayerObject = player.GetComponent<GameObject>();. Again, GetComponent is a nonstatic method so can not be called in a global setting. The other issue is GameObject is not a component, it is a type. GameObjects have components so you can not get the component of itself as it does not exist. You are already using Transform.Find which finds a transform, I would recommend just finding the GameObject, storing that reference then get the Transform from the gameObject. You do not really need to store the transform as its own reference if you have the GameObject reference though.
public Transform player;
public GameObject PlayerObject;
private void Start()
{
PlayerObject = GameObject.Find(playername);
player = PlayerObject.transform;
}
The final error being outputted is specifying that you are using LookAt incorrectly. You need to pass in a type of Transform, but you are passing in a type of GameObject. Change it to...
t.LookAt(player);
Most of these issues are rather trivial and straightforward. I would follow along with a tutorial or read through the docs to get a better understanding of C#/Unity/Programming. Being a beginner is fine, but StackOverflow should not just be used as debugging help when the errors are right there. I do not know if the 4 recommendations I mentioned will fully fix your program as I did not run it. There could be more issues than what I had mentioned, but following the errors should tell you what is wrong and why it is wrong. It is printing the line number, file, and reason for why it is breaking.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed;
private void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player")) {
other.GetComponent <Player> ().health -= damage;
Debug.Log(other.GetComponent<Player>().health);
Destroy(gameObject);
}
}
}
The lines
other.GetComponent <Player> ().health -= damage;
Debug.Log(other.GetComponent<Player>().health);
are what cause the error.
This is the error that comes up:
Assets\Scripts\Obstacle.cs(17,33): error CS0246: The type or namespace name 'Player' could not be found (are you missing a using directive or an assembly reference?)
Any help would be greatly appreciated and I apologise if this is a stupid question, I am very new to c# and Unity
You should have (or create) Player.cs script (class) in your project.
It can be created in Project tab with a right mouse button: Create/C# Script.
It can look like this to avoid your exception (error):
using UnityEngine;
public class Player : MonoBehaviour
{
public float health = 5;
}
Also potentially you want to kill (destroy) object if Life is going bellow or equal 0. In this case your script can look like this:
using UnityEngine;
public class Obstacle : MonoBehaviour
{
public int damage = 1;
public float speed = 1;
void Update()
{
transform.Translate(Vector2.left * speed * Time.deltaTime);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("Player"))
{
Player player = other.GetComponent<Player>();
//If "other" Game Object has Player component.
if (player)
{
player.health -= damage;
Debug.Log(player.health);
if(player.health <= 0)
{
Destroy(gameObject);
}
}
}
}
}
Cheers!
having a slight problem. I am reworking a project of mine using SpriteFactory, and have used a youtube following the exact same code as his but running into the following error:
using UnityEngine;
using System.Collections;
using SpriteFactory;
public class Running : MonoBehaviour {
private SpriteFactory.Sprite;
// Use this for initialization
void Start () {
sprite = GetComponent<Sprite> ();
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.RightArrow)) {
Sprite.Play("Run");
Vector3 pos = transform.position;
pos.x += Time.deltaTime * 2;
transform.position = pos;
}
else{
sprite.Stop();
}
}
}
Error It results in is Unexpected Symbol ";" in class, struct or interface member declaration which i know is referring to:
private SpriteFactory.Sprite;
but I am not even sure why? Suggestions
Here you go :)
using UnityEngine;
using System.Collections;
// below solved conflict of class names
// we won't "using" whole SpriteFactory namespace because
// both UnityEngine and SpriteFactory have got same class "Sprite"
// so we pull out only needed class
using FactorySprite = SpriteFactory.Sprite;
public class Running : MonoBehaviour {
// you forgot to set name of variable representing your sprite
private FactorySprite sprite;
// Use this for initialization
void Start () {
sprite = GetComponent<FactorySprite> (); // Edited
}
// Update is called once per frame
void Update () {
if(Input.GetKey(KeyCode.RightArrow)) {
sprite.Play("Run"); // heh, remember C# is case sensitive :)
Vector3 pos = transform.position;
pos.x += Time.deltaTime * 2;
transform.position = pos;
}
else{
sprite.Stop();
}
}
}