I cant fix error CS1001: Identifier expected - c#

here is my player attach code for moving platforms:
I'm getting an error CS1001: Identifier expected for some reason ant youtube is not helping me...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerAttach : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
function OnTriggerEnter(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = other.transform;
}
}
function OnTriggerExit(other.Collider){
if (other.gameObject.tag == "player")
{
transform.parent = null;
}
}
}
}

What you have is unityscript which is long deprecated and not compatible with c#!
And in general do not nest MonoBehaviour messages under Update! Otherwise the messaging system won't find them and they are never called at all.
Your class should look like
public class PlayerAttach : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
// Rather use CompareTag instead of ==
// the latter fails silently in case of s typo making your debugging live only harder
if (!other.CompareTag("player")) return;
transform.parent = other.transform;
}
private void OnTriggerExit(Collider other)
{
if (!other.CompareTag("player")) return;
transform.parent = null;
}
}
Further, a logical question: How exactly do you expect the player object leaving this collider if you make it a parent so whenever the player object moves this object moves along with it?

Related

unity animation not working receiveing error when i press allocated key saying Invalid Layer Index '-1'

i used animation in unity, i had my c# code, i used a similar code for another function that worked but however when i used it for this function which is the door opening animation it didnt work
this is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class door : MonoBehaviour
{
public GameObject txttodisplay;
private bool Playerinzone;
// Start is called before the first frame update
void Start()
{
txttodisplay.SetActive(false);
Playerinzone = false;
}
// Update is called once per frame
void Update()
{
if (Playerinzone && Input.GetKeyDown(KeyCode.O))
{
gameObject.GetComponent<Animator>().Play("door");
}
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player")
{
Playerinzone = true;
txttodisplay.SetActive(true);
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Player")
{
Playerinzone = false;
txttodisplay.SetActive(false);
}
}
}
this is the error i received when i press "O" which is the key i need to press to activate the animation
Invalid Layer Index '-1'
UnityEngine.Animator:Play (string)
door:Update () (at Assets/scripts/doorScript/door.cs:24)
for the door i used a free asset from unity asset store and i linked the script to the door
any help?

In unity what is C# jump script showing error

On unity using C# I made this jump script to control a player. When I run the code below I get the errors shown below
using UnityEngine;
public class PlayerScript : MonoBehaviour
{
public float JumpForce;
[SerializeField]
bool isGrounded = false;
Rigidbody2D RB;
private void Awake()
{
RB = GetComponent<Rigidbody2D();
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{
if(isGrounded == true)
{
RB.AddForce(Vector2.up*JumpForce);
isGrounded = false;
}
}
}
O refrences
private void OnCollisionEnter2D(Collision2D collision)
{
if(collision.gameObject.CompareTag("ground"))
{
if(isGrounded == false)
{
isGrounded = true;
}
}
}
}
For some reason, I get no error inside of vs code but when I to the game it says what the picture below says. If you have an answer it would really help thanks.
Make sure you have configured everything correctly. An in-depth tutorial can be found here.
https://code.visualstudio.com/docs/other/unity
The warnings can happen when you change the name of a class or file and don't fix the script component on the scene game object. It can also give that warning if you change the code while in playmode.

Retrive objects from a list and teleport them to a specific location in Unity

and thank you for looking at this in advance.
I have yet another problem that i need to solve and it goes like this:
I have a list of objects that i select with a raycast, and i would like to teleport them to a specific location in the scene. Like for example i have selected a cube and a sphere and they are added to my list called playersTagged.
How can i get the objects in my list to that specific location when OnCollisionEnter with my player that has the tag "Tagger"?
My code looks like this:
PlayerTagged Class
using System.Collections.Generic;
using UnityEngine;
public class PlayerTagged : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public List<GameObject> playersTagged;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null && target.isHit == false)
{
target.takeDamage(damage);
if(hit.collider.tag == "Taggable")
playersTagged.Add(hit.collider.gameObject);
target.isHit = true;
}
}
}
}
Teleport class:
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
}
}
}
You need to have the PlayerTagged reference in your Teleport component. If both objects will always exist in your scene, only create a public field in your Teleport and drag and drop your PlayerTagged ref, otherwise you will need to fill this ref by code using some "find" approach, for example, GameObject.FindObjectWithTag().
You can also make an event that trigger when the object that entered the OnTriggerEnter is valid (I mean, when your tag condition pass) and then make sure that PlayerTagged is being registered as listener to this event.
First one is easier to setup, but if you plan to make unique things with this OnTriggerEnter as playing sounds, changing data or something like that, the second one is a better approach.
EDIT: I'll try to insert some code, let me know if you still having problems on getting the idea
"If both objects will always exist in your scene..."
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player; // I didn't saw that you already have an ref here, my bad, so you only need to access the fields
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
var list = player.playersTagged; // this is how you will access your list
// Do some stuff with your list
}
}
}
Ignore the rest, it will only complicate things
EDIT 2: Making the teleport happen in player, and teleport every object
using System.Collections.Generic;
using UnityEngine;
public class PlayerTagged : MonoBehaviour
{
public float damage = 10f;
public float range = 100f;
public Camera fpsCam;
public List<GameObject> playersTagged;
private void Update()
{
if (Input.GetButtonDown("Fire1"))
{
Shoot();
}
}
// Option 1:
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.tag == "Teleport Tag")
{
var teleport = col.gameObject.GetComponent<Teleport>();
TeleportObjectsTo(teleport.teleportTarget.position);
}
}
void Shoot()
{
RaycastHit hit;
if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
{
Debug.Log(hit.transform.name);
Target target = hit.transform.GetComponent<Target>();
if (target != null && target.isHit == false)
{
target.takeDamage(damage);
if(hit.collider.tag == "Taggable")
playersTagged.Add(hit.collider.gameObject);
target.isHit = true;
}
}
}
public void TeleportObjectsTo(Vector3 targetPosition)
{
foreach(taggedObjects in playersTagged)
{
taggedObjects.transform.position = targetPosition;
}
}
}
You can also make the teleport happen on teleport script:
using UnityEngine;
public class Teleport : MonoBehaviour
{
public Transform teleportTarget;
public PlayerTagged player; // I didn't saw that you already have an ref here, my bad, so you only need to access the fields
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Tagger")
{
Debug.Log("You hit the can");
// Option 2:
player.TeleportObjectsTo(teleportTarget);
// Option 3: Or you can iterate here instead of make use of the API
foreach(var taggedObjects in player.playersTagged)
{
taggedObjects.transform.position = targetPosition;
}
}
}
}
Chose one option, and delete/comment others
--N

reference from various scripts causing problems [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 1 year ago.
For some reason when I'm in the normal view in-game I am able to link the scripts that I need to call in order to make an animation like so
however, whenever I start the game it automatically removes them from the slots, and it doesn't work
I am completely clueless as to why this may be happening and unity keep giving me errors that say that I'm not setting an instance to my script I really have no clue why this may be happening.
I have 3 scripts that I'm working with that is giving me the problem
one is the main script for the enemy vision (I am referencing the other scripts in this one)
the second is the enemy animation script which makes him go from idle to attack and the third is an animation for the gun model since I had to make it follow the hands of the enemy
scripts attached bellow
1st script(enemyAI):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAi : MonoBehaviour
{
public bool detected;
GameObject target;
public Transform enemy;
public GameObject Bullet;
public Transform shootPoint;
public float shootSpeed = 10f;
public float timeToShoot = 1f;
public EnemyAni Animation;
public GunAni GunAnimation;
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
public void Update()
{
//makes the enemy rotate on one axis
Vector3 lookDir = target.transform.position - transform.position;
lookDir.y = 0f;
//makes enemy look at the players position
if (detected)
{
enemy.LookAt(target.transform.position, Vector3.up);
enemy.rotation = Quaternion.LookRotation(lookDir, Vector3.up);
}
if (detected == true)
{
Animation.LookPlayer = true;
GunAnimation.ShootPlayer = true;
}
if (detected == false)
{
Animation.LookPlayer = false;
GunAnimation.ShootPlayer = false;
}
}
//detects the player
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
detected = true;
target = other.gameObject;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
detected = false;
}
}
}
2nd Script (EnemyAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAni : MonoBehaviour
{
public Animator animator;
public bool LookPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (LookPlayer == true)
{
animator.SetBool("IsShootingStill", true);
}
else
{
animator.SetBool("IsShootingStill", false);
}
}
}
3rd script (GunAnimation):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunAni : MonoBehaviour
{
public Animator animator;
public bool ShootPlayer;
public void Start()
{
animator = GetComponent<Animator>();
}
public void Update()
{
if (ShootPlayer == true)
{
animator.SetBool("IsShooting", true);
}
else
{
animator.SetBool("IsShooting", false);
}
}
}
Your code:
void Start()
{
Animation = GetComponent<EnemyAni>();
GunAnimation = GetComponent<GunAni>();
}
Searches the GameObject that holds the EnemyAI script for EnemyAni and GunAni. If the GameObject doesn't have those it will return null.
Sounds like you want to remove that code.
Note that if the scripts exist on a child of that GameObject you will need to use GetComponentInChildren
There are some things to review, good practices:
GameObject target is private for C#, but it is better to put private before.
variable names like Bullet Animation GunAnimation should always begin with lowercase, because they might be confused with a Class Name (search in internet for CamelCase and PascalCase).
Name should be clear. EnemyAni Animation is not clear enough, because Animation maybe any animation (player, enemy, cube, car, etc.).
It is better enemyAnimation to be clear, as you did with GunAnimation (only just with lower case at beginning)
As slaw said, the Animation must be in the GO attached.
about last item
Let's say you have an empty GO (GameObject) called GameObject1 and you attach EnemyAi script to it.
In Runtime (when game mode begins), it will try to find Animation = GetComponent<EnemyAni>();, but it won't find it
Why?
Because GetComponent<> searches for the Component(Class) that is in the <> (in this case EnemyAni) in its GO (in this case, GameObject1), but the unique script attached to GameObject1 is EnemyAI.
So, you have 3 options:
Attach EnemyAni to GameObject1
Create another GO (for example, GameObjectEnemyAni), attach the script EnemyAni and drag and drop GameObjectEnemyAni to GameObject1 and delete Animation = GetComponent<EnemyAni>(); in Start
Keep in mind: if you leave that line of code, instead of getting the script EnemyAni from GameObjectEnemyAni, it will run the code Animation = GetComponent<EnemyAni>(); in Start, and obviously, it won't find it
Create events. It's a really good practice for avoiding code tight coupling, but that is more advanced stuff.

Health system script not running in Unity; no errors or Debug.Log statements popping up

For my health system in a Unity game, I have a script that is accountable for my in-game "enemy" hit-points. The game runs just fine, but the script doesn't seem to be doing anything. I'm not getting any error messages, but the fact that it's not working and Debug.Log statements aren't popping up in console seem to be that functions aren't being called properly or that something else is awry. Here is my script:
using System.Diagnostics;
using UnityEngine;
public class Health : MonoBehaviour {
private float hitPoints = 5;
// Health popup
void announceUp()
{
UnityEngine.Debug.Log("If this message shows in Debug.Log, the script should be working.");
}
// Update is called once per frame
void Update()
{
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Bullet")
{
UnityEngine.Debug.Log("The enemy has been hit!");
hitPoints = hitPoints - 1f;
if (hitPoints == 0f)
{
UnityEngine.Debug.Log("The enemy has been eliminated!");
Destroy(gameObject);
}
}
}
}
}
I've poked around the internet to see what's wrong, but I couldn't find anything. Could someone inform me on what could be wrong with my programming?
Your scrpt is currently not working, because you are defining the OnTriggerEnter() Method inside the Update() Method. When you do that you are defining a local function and Unity then can't call that function when actual collision happens. So your OnTriggerEnter() Function never get's called.
Example:
using System.Diagnostics;
using UnityEngine;
public class Health : MonoBehaviour
{
private float hitPoints = 5;
// Health popup
void announceUp() {
UnityEngine.Debug.Log("If this message shows in Debug.Log,
the script should be working.");
}
// Update is called once per frame
void Update() {}
void OnTriggerEnter(Collider other) {
if (other.gameObject.tag == "Bullet") {
UnityEngine.Debug.Log("The enemy has been hit!");
hitPoints = hitPoints - 1f;
if (hitPoints == 0f) {
UnityEngine.Debug.Log("The enemy has been eliminated!");
Destroy(gameObject);
}
}
}
}

Categories

Resources