CS1001 Identifier Expected in Unity - c#

Basically I've been trying fix this error for ages so I can actually look at thee game in play mode. It is a script for enemy AI who will chase the player around.
The error is at (90,32) which is attempting to transform the enemys vision when they attack the player
The line that is creating the issue is transform LookAt(player);
Any help would be much appreciated.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyAI : MonoBehaviour
{
public NavMeshAgent agent;
public Transform player;
public LayerMask whatIsGround, whatIsPlayer;
public int Damage = 5;
//Patrolling
public Vector3 walkPoint;
bool walkPointSet;
public float walkPointRange;
//Attacking
public float timeBetweenAttacks;
bool alreadyAttacked;
//States
public float sightRange, attackRange;
public bool playerInSightRange, playerInAttackRange;
private void Awake()
{
player = GameObject.Find("player").transform;
agent = GetComponent<NavMeshAgent>();
}
private void Update()
{
//Check for attack and sight range
playerInSightRange = Physics.CheckSphere(transform.position, sightRange, whatIsPlayer);
playerInAttackRange = Physics.CheckSphere(transform.position, attackRange, whatIsPlayer);
if (!playerInSightRange && !playerInAttackRange) Patrolling();
if (playerInSightRange && !playerInAttackRange) ChasePlayer();
if (playerInSightRange && playerInAttackRange) AttackPlayer();
}
private void Patrolling()
{
if (!walkPointSet) SearchWalkPoint();
if (walkPointSet)
agent.SetDestination(walkPoint);
Vector3 distanceToWalkPoint = transform.position - walkPoint;
//when walkpoint is reached
if (distanceToWalkPoint.magnitude < 1f)
walkPointSet = false;
}
private void SearchWalkPoint()
// Will calculate and random point on the x and z axis
{
float randomZ = Random.Range(-walkPointRange, walkPointRange);
float randomX = Random.Range(-walkPointRange, walkPointRange);
walkPoint = new Vector3(transform.position.x + randomX, transform.position.y, transform.position.z + randomZ);
if (Physics.RayCast(walkPoint, -transform.up, 2f, whatIsGround))
walkPointSet = true;
}
private void ChasePlayer()
{
agent.SetDestination(player.position);
}
private void AttackPlayer()
{
agent.SetDestination(transform.position);
transform LookAt(player);
if (!alreadyAttacked)
{
alreadyAttacked = true;
invoke(nameof(ResetAttack), timeBetweenAttacks);
}
}
private void ResetAttack()
{
alreadyAttacked = false;
}
void OnTriggerEnter(Collider other)
{
Debug.Log("Collison");
if (other.gameObject.tag == "player")
{
if (other.gameObject.GetComponent<Health>() == true)
{
other.gameObject.GetComponent<Health>().TakeDamage(Damage);
}
}
}
}

Identifier Expected in Unity
Means the syntax is incorrect, meaning you've written incorrect code.
transform LookAt(player);
should be
transform.LookAt(player);
whitespace ( ) is not an operator or identifier, and does nothing to the transform. In order to access the properties/methods of the GameObject's transform, you use a dot (.). In this case, you're accessing the transform's LookAt method.

There will be a error:
Change: invoke(nameof(ResetAttack), timeBetweenAttacks); => Invoke(nameof(ResetAttack), timeBetweenAttacks);

Related

How to make Enemy FLIP and ATTACK in Unity2D?

I was following a tutorial for creating an enemy in Unity, but they didn't teach how to flip the enemy in case the Player goes to the other side of the map, oppose to where the enemy is.
So I tried to increase the raycast area, so when the Player collides with it from behind, the enemy will know that it has to flip. But something isn't working, cause it goes fine to the Player when it's facing the left side of the map, but once it flips, it totally stops working, and I can't figure it out why.
Anyone have any idea what should I do?
Here is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Skeleton : MonoBehaviour
{
#region Public Variables
public Transform rayCast;
public LayerMask raycastMask;
public GameObject target;
public float rayCastLength;
public float attackDistance; //Mininum distance to attack
public float moveSpeed;
public float timer; // Cooldown b/w attacks
public bool inRange; //check if the player is near
#endregion
#region Private Variables
private RaycastHit2D hit;
private Animator anim;
private float distance; //Distance b/w enemy and player
public bool attackMode;
private float intTimer;
#endregion
void Awake() {
intTimer = timer;
anim = GetComponent<Animator>();
}
void Update() {
if (inRange)
{
hit = Physics2D.Raycast(rayCast.position, Vector2.left, rayCastLength, raycastMask);
}
//When the player is detected
if(hit.collider != null)
{
EnemyLogic();
}
// If it's not inside the raycast
else if(hit.collider == null)
{
inRange = false;
}
// If the player leaves the range
if (inRange == false)
{
anim.SetBool("canWalk", false);
StopAttack();
anim.SetInteger("Idle", 0);
}
}
void OnTriggerEnter2D(Collider2D col)
{
if(col.gameObject.tag == "Player")
{
target = col.gameObject;
inRange = true;
Flip();
}
}
void EnemyLogic()
{
distance = Vector2.Distance(transform.position, target.transform.position);
if(distance > attackDistance)
{
Move();
StopAttack();
}
else if(attackDistance >= distance)
{
Attack();
}
}
void Move()
{
anim.SetInteger("Idle", 1);
anim.SetBool("canWalk", true);
if (!anim.GetCurrentAnimatorStateInfo(0).IsName("attack"))
{
Vector2 targetPosition = new Vector2(target.transform.position.x, transform.position.y);
transform.position = Vector2.MoveTowards(transform.position, targetPosition, moveSpeed * Time.deltaTime);
}
}
void Attack()
{
timer = intTimer; //reset timer
attackMode = true;
anim.SetInteger("Idle", 1);
anim.SetBool("canWalk", false);
anim.SetBool("Attack", true);
}
void StopAttack()
{
attackMode = false;
anim.SetBool("Attack", false);
}
// Detects if the player is on the other side
void Flip()
{
Vector3 rotation = transform.eulerAngles;
if(target.transform.position.x < transform.position.x)
{
rotation.y = 180f;
}
else
{
rotation.y = 0f;
}
transform.eulerAngles = rotation;
}
}
You can flip the enemy using localScale. Do this:
if (Player.transform.position.x < this.transform.position.x)
{
transform.localScale = new Vector3(-1, 1, 1);
}else
{
transform.localScale = new Vector3(1, 1, 1);
}
This detects whenever the player's x position is greater or lower than the enemy and flips the whole object.

How do I make my player speed up when collide with a game object in Unity?

I am doing a school project in Unity. My team and I decided to make an endless runner 2D game. However, because it is the first time I use C#, I don't know how to make my player's speed accelerate when collide with a game object in Unity. I only know how to destroy the player's health when a collision happens. Please help me! Thank you!
it's quite hard to give answers without seeing any code you've written, but as it's 2D and you've already got the collision damage working, you've probably used an OnCollisionEnter(), well it's very similar: you test if you've collided (which you've already done), then you add force to your player using a rigidbody2d, probably something along the lines of:
public Rigidbody2D rb;
void OnCollisionEnter2D(Collision2D collision)
{
rb.AddForce(direction * force, ForceMode2D.Impulse); // the ForceMode2D is
// optional, it's just so that
// the velocity change is sudden.
}
This should work.
If you have a GameManager that stores the game speed you can also do that too:
private float gameSpeedMultiplier = 0.5f;
void OnCollisionEnter(Collision collision)
{
if(collision.gameObject.CompareTag("Tag of the collided object")
{
GameManager.Instance.gameSpeed += gameSpeedMultiplier;
}
}
public class PlayerContoler : MonoBehaviour
{
public static PlayerContoler instance;
public float moveSpeed;
public Rigidbody2D theRB;
public float jumpForce;
private bool isGrounded;
public Transform GroundCheckPoint;
public LayerMask whatIsGround;
private bool canDoubleJump;
private Animator anim;
private SpriteRenderer theSR;
public float KnockbackLength, KnockbackForce;
private float KnockbackCounter;
public float bonceForce;
public bool stopImput;
private void Awake()
{
instance = this;
}
// Start is called before the first frame update
void Start()
{
anim = GetComponent<Animator>();
theSR = GetComponent<SpriteRenderer>();
}
// Update is called once per frame
void Update()
{
if(!PauseMenu.instance.isPause && !stopImput)
{
if (KnockbackCounter <= 0)
{
theRB.velocity = new Vector2(moveSpeed * Input.GetAxis("Horizontal"), theRB.velocity.y);
isGrounded = Physics2D.OverlapCircle(GroundCheckPoint.position, .2f, whatIsGround);
if (isGrounded)
{
canDoubleJump = true;
}
if (Input.GetButtonDown("Jump"))
{
if (isGrounded)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
AudioManager.instance.PlaySFX(10);
}
else
{
if (canDoubleJump)
{
theRB.velocity = new Vector2(theRB.velocity.x, jumpForce);
canDoubleJump = false;
AudioManager.instance.PlaySFX(10);
}
}
}
if (theRB.velocity.x < 0)
{
theSR.flipX = true;
}
else if (theRB.velocity.x > 0)
{
theSR.flipX = false;
}
} else
{
KnockbackCounter -= Time.deltaTime;
if(!theSR.flipX)
{
theRB.velocity = new Vector2(-KnockbackForce, theRB.velocity.y);
} else
{
theRB.velocity = new Vector2(KnockbackForce, theRB.velocity.y);
}
}
}
anim.SetFloat("moveSpeed", Mathf.Abs(theRB.velocity.x));
anim.SetBool("isGrounded", isGrounded);
}
public void Knockback()
{
KnockbackCounter = KnockbackLength;
theRB.velocity = new Vector2(0f, KnockbackForce);
anim.SetTrigger("hurt");
}
}

I am trying to do a score that increase on ball collision with brick

I am doing a game in Unity for a school project.
I need to increase the score when the ball collides with brick. What I am doing wrong please? Below is the code that I tried to use. Score starts at zero but never goes more than 1. Any help of how I can fix this issue please?
public class Brick : MonoBehaviour
{
public int hitPoint = 3;
public GameObject explosion;
public GameObject heart;
[Range(0f, 1f)]
public float percentage;
float randNum;
public float fallSpeed = 8.0f;
public Sprite OneHits;
public Sprite TwoHits;
public Sprite ThreeHits;
public Text ScoreText;
private int points;
GameObject ball;
void Start()
{
ball = GameObject.FindGameObjectWithTag("ball");
}
void Update()
{
ScoreText.text = "Score " + points ;
randNum = Random.Range(0f, 1f);
if (hitPoint == 1)
{
this.GetComponent<SpriteRenderer>().sprite = OneHits;
}
if (hitPoint == 2)
{
this.GetComponent<SpriteRenderer>().sprite = TwoHits;
}
if (hitPoint == 3)
{
this.GetComponent<SpriteRenderer>().sprite = ThreeHits;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "ball")
{
ball = collision.gameObject;
hitPoint--;
points++;
if (hitPoint <= 0)
{
Destroy(this.gameObject);
Instantiate(explosion, transform.position, transform.rotation);
if (randNum < percentage)
{
Instantiate(heart, transform.position, transform.rotation);
}
}
}
}
}
There are a couple of things wrong with your code.
If you destroy the game object the script is running on the script will stop, so I would move your destroy command to the end of your method.
I am guessing that you dont want points to be different for each brick, I would move points to another class called scoreboard or something. For the time being I made points static. This means that only one copy of this variable exists and if one brick adds a point it gets reflected across all bricks.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public int hitPoint = 3;
public GameObject explosion;
public GameObject heart;
[Range(0f, 1f)]
public float percentage;
float randNum;
public float fallSpeed = 8.0f;
public Sprite OneHits;
public Sprite TwoHits;
public Sprite ThreeHits;
public Text ScoreText;
public static int points;
GameObject ball;
void Start()
{
ball = GameObject.FindGameObjectWithTag("ball");
}
void Update()
{
ScoreText.text = "Score " + points;
randNum = Random.Range(0f, 1f);
if (hitPoint == 1)
{
this.GetComponent<SpriteRenderer>().sprite = OneHits;
}
if (hitPoint == 2)
{
this.GetComponent<SpriteRenderer>().sprite = TwoHits;
}
if (hitPoint == 3)
{
this.GetComponent<SpriteRenderer>().sprite = ThreeHits;
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("ball"))
{
ball = collision.gameObject;
hitPoint--;
points++;
if (hitPoint <= 0)
{
Instantiate(explosion, transform.position, transform.rotation);
if (randNum < percentage)
{
Instantiate(heart, transform.position, transform.rotation);
}
Destroy(gameObject);
}
}
}
}

How to change hit point to crosshair?

Below script uses a function whereas there first is a check if there is a object in range and if it, it is.
On pressing mouse key, the projectile is shooting towards the pivot point of that said object. I want the projectile to
always being able to fire (indifferent if the object is in range) and
shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.
I am a novice at coding and I can't see what code to remove and what to add.
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
public struct ShootHit
{
public GameObject gameObject;
public Vector3 point;
}
[System.Serializable]
public class UnityEventShootHit : UnityEvent<ShootHit> { }
[DisallowMultipleComponent, AddComponentMenu("(つ♥v♥)つ/Useables/Shoot")]
public class ShootComponent : MonoBehaviour
{
[Header("Input")]
[Tooltip("Data that determines the input of player actions")]
[SerializeField] private InputProfile _inputProfile;
// [SerializeField] private float _range = 100.0f;
/* [Header("Sight Values")]
[Tooltip("How far the the sight can reach")]
public float sightRadius = 1f;
[Range(0f, 360f)]
public float fieldOfViewAngle = 100f;*/
[Header("Charge-up")]
[SerializeField] private float _chargeupTime = 0.5f;
private bool _isChargingPrimary = false;
private bool _isChargingSecondary = false;
[Header("Aim Assist")]
[SerializeField] private LayerMask _aimAssistLayerMask;
public float aimAssistRadius = 30.0f; // radius
[Range(0.0f, 360.0f)]
public float aimAssistMaxAngleToAssist = 45.0f; // angle
private ShootHit? _target;
//publics
public Transform shootOrigin;
[Header("Events")]
public UnityEventShootHit OnPrimaryFire;
public UnityEvent OnPrimaryFireStart;
public UnityEvent OnPrimaryFireStop;
public UnityEventShootHit OnSecondaryFire;
public UnityEvent OnSecondaryFireStart;
public UnityEvent OnSecondaryFireStop;
private void Start()
{
if (_inputProfile == null) Debug.LogError(gameObject.name + " does not
have a player input");
}
private void Update()
{
// Remove target if object is too far away
if (_target.HasValue)
{
if (Vector3.Distance(_target.Value.gameObject.transform.position,
transform.position) > aimAssistRadius)
{
_target = null;
}
}
if (_inputProfile.GetPrimaryFireButtonDown())
{
StopCoroutine(ChargeUpBeforeFireSecondary());
if (!_isChargingPrimary)
{
StartCoroutine(ChargeUpBeforeFirePrimary());
}
}
else if (_inputProfile.GetSecondaryFireButtonDown())
{
StopCoroutine(ChargeUpBeforeFirePrimary());
if (!_isChargingSecondary)
{
StartCoroutine(ChargeUpBeforeFireSecondary());
}
}
if (_inputProfile.GetPrimaryFireButton() ||
_inputProfile.GetSecondaryFireButton())
{
if (!_target.HasValue) _target = GetObjectClosestToAim();
if (_inputProfile.GetPrimaryFireButton())
{
OnPrimaryFire.Invoke(_target.Value);
}
if (_inputProfile.GetSecondaryFireButton())
{
OnSecondaryFire.Invoke(_target.Value);
}
}
else
{
_target = null;
}
if (_inputProfile.GetPrimaryFireButtonUp())
OnPrimaryFireStop.Invoke();
if (_inputProfile.GetSecondaryFireButtonUp())
OnSecondaryFireStop.Invoke();
}
/// <summary>
/// Finds the object within range closest to the players forward-vector
using _aimAssistLayerMask.
/// </summary>
/// <returns>Returns object closest to aim if any object is found, else
returns null.</returns>
ShootHit? GetObjectClosestToAim()
{
// Raycast
RaycastHit hit;
if (Physics.Raycast(shootOrigin.position, Camera.main.transform.forward,
out hit, aimAssistRadius, _aimAssistLayerMask))
{
if (hit.transform?.GetComponent<IShootTarget>() != null)
{
Debug.Log(hit.transform.name);
return new ShootHit { gameObject = hit.transform.gameObject,
point = hit.point };
}
}
float _closestDot = -2f;
GameObject _closestDotObject = null;
RaycastHit[] _hit = Physics.SphereCastAll(transform.position,
aimAssistRadius, transform.forward, 0, _aimAssistLayerMask,
QueryTriggerInteraction.Ignore);
// Get best dot from all objects within range
for (int i = 0; i < _hit.Length; i++)
{
if (_hit[i].transform.gameObject == this.gameObject ||
_hit[i].transform.GetComponent<IShootTarget>() == null)
continue;
Vector3 _dif = _hit[i].transform.position - transform.position;
float _newDot = Vector3.Dot(transform.forward.normalized,
_dif.normalized);
if (_newDot > _closestDot)
{
_closestDot = _newDot;
_closestDotObject = _hit[i].transform.gameObject;
}
}
if (!_closestDotObject)
return null;
// Make sure there are no object in the way of our best-dot-object
Collider[] colliders = _closestDotObject.GetComponents<Collider>();
Vector3 point = colliders[0].ClosestPoint(shootOrigin.position);
float distanceToPoint = Vector3.Distance(shootOrigin.position, point);
// Get closest collider
for (int i = 1; i < colliders.Length; i++)
{
Vector3 newPoint = colliders[i].ClosestPoint(shootOrigin.position);
float newDistanceToPoint = Vector3.Distance(shootOrigin.position,
newPoint);
if (distanceToPoint > newDistanceToPoint)
{
point = newPoint;
distanceToPoint = newDistanceToPoint;
}
}
RaycastHit _rayhit;
if (Physics.Raycast(shootOrigin.position, point - transform.position,
out _rayhit, aimAssistRadius, _aimAssistLayerMask))
{
if (_rayhit.transform.gameObject != _closestDotObject)
{
return null;
}
}
Vector3 _vecToClosest = _closestDotObject.transform.position -
transform.position;
if (Vector3.Angle(transform.forward, _vecToClosest) <=
aimAssistMaxAngleToAssist)
{
return new ShootHit { gameObject = _closestDotObject, point = point
};
}
else
{
return null;
}
}
IEnumerator ChargeUpBeforeFirePrimary()
{
_isChargingPrimary = true;
yield return new WaitForSeconds(_chargeupTime);
_isChargingPrimary = false;
OnPrimaryFireStart.Invoke();
}
IEnumerator ChargeUpBeforeFireSecondary()
{
_isChargingSecondary = true;
yield return new WaitForSeconds(_chargeupTime);
_isChargingSecondary = false;
OnSecondaryFireStart.Invoke();
}
#if UNITY_EDITOR
private void OnDrawGizmosSelected()
{
if (!Application.isPlaying) return;
Color oldColor = Gizmos.color;
float halfFeildOfView = aimAssistMaxAngleToAssist * 0.5f;
float coneDirection = -90f;
Quaternion leftRayRotation = Quaternion.AngleAxis(-halfFeildOfView + coneDirection, Vector3.up);
Quaternion rightRayRotation = Quaternion.AngleAxis(halfFeildOfView + coneDirection, Vector3.up);
Vector3 leftRayDirection = leftRayRotation * transform.right * aimAssistRadius;
Vector3 rightRayDirection = rightRayRotation * transform.right * aimAssistRadius;
// Green Arc
Handles.color = new Color(0f, 1f, 0f, 0.25f);
Handles.DrawSolidArc(transform.position, Vector3.up, leftRayDirection, aimAssistMaxAngleToAssist, aimAssistRadius);
Gizmos.color = oldColor;
}
#endif
}
`
This is the code attached to the projectile
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(Rigidbody))]
public class ProjectileScript : MonoBehaviour
{
public GameObject Explosion;
public Transform Target;
Rigidbody _rigidbody;
public float speed = 1.0f;
void Start()
{
_rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
// _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
Collider targetCollider = Target.GetComponent<Collider>();
Vector3 targetDirection;
if (targetCollider)
targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
else
targetDirection = Target.position - transform.position;
_rigidbody.velocity = targetDirection.normalized * speed;
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
}
public void SetTarget(GameObject target)
{
this.Target = target.transform;
}
public void SetTarget(ShootHit hit) => SetTarget(hit.gameObject);
}
This script is how and where the Projectile Spawns. It is attached to an empty gameobject located on the muzzle of the gun.
public class ProjectileSpawner : MonoBehaviour
{
public GameObject projectileInsert;
public GameObject projectileExtract;
public float projectileSpeed = 1.0f;
GameObject projectile;
public void Insert(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(target);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
public void Extract(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(gameObject);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
}
In the ProjectileSpawner, add a LayerMask field to filter out invalid collisions (set it in the inspector) for the non-homing projectile. You'll set this in the inspector to make the non-homing projectiles collide with the desired layers:
public LayerMask collisionLayers;
In Insert, find the ray going from the screen's center, and use it and the LayerMask as a parameter to SetTarget:
public void Insert(GameObject target)
{
if (projectile) return;
Ray centerRay = Camera.main.ScreenPointToRay(new Vector3(Screen.width/2, Screen.height/2, 0f));
projectile = Instantiate(projectileInsert, transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(centerRay, collisionLayers);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
public void Extract(GameObject target)
{
if (projectile) return;
projectile = Instantiate(projectileExtract, target.transform.position, Quaternion.identity);
ProjectileScript projectileScript = projectile.GetComponent<ProjectileScript>();
projectileScript.SetTarget(gameObject);
projectileScript.speed = projectileSpeed;
// Physics.IgnoreCollision(projectile.GetComponent<Collider>(),
// projectileSpawn.parent.GetComponent<Collider>());
}
Then in the ProjectileScript, add a bool field to remember if the projectile homes on a gameObject or if it follows a ray, a Ray field to remember such a ray, and a LayerMask field to remember what to collide with:
public bool isHoming;
public Ray TargetRay
public LayerMask collisionLayers;
Then, in public void SetTarget(GameObject target), set that bool to true:
public void SetTarget(GameObject target)
{
this.Target = target.transform;
isHoming = true;
}
And make a new public void SetTarget(Ray shootRay) that remembers a Ray and LayerMask and sets the bool to false:
public void SetTarget(Ray shootRay, LayerMask collisionLayers)
{
this.TargetRay = shootRay;
this.collisionLayers = collisionLayers;
isHoming = false;
}
Also, in ProjectileScript, you will need to change the FixedUpdate method to check if the bool is true, and if it is, then do the same as before. Otherwise, move along the ray and destroy it if it travels too far:
public float maxDistanceBeforeDestroy = 100f;
...
void FixedUpdate()
{
if (isHoming)
{
// _rigidbody.AddForce((Target.position - transform.position).normalized, ForceMode.Impulse);
Collider targetCollider = Target.GetComponent<Collider>();
Vector3 targetDirection;
if (targetCollider)
targetDirection = targetCollider.ClosestPoint(transform.position) - transform.position;
else
targetDirection = Target.position - transform.position;
_rigidbody.velocity = targetDirection.normalized * speed;
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
}
else
{
_rigidbody.velocity = TargetRay.direction.normalized * speed;
// Check if it has traveled too far
if ((transform.position - TargetRay.origin).magnitude > maxDistanceBeforeDestroy )
{
Destroy(gameObject);
}
}
}
Then, add an OnCollisionEnter method that doesn't do anything if the projectile is homing. But if it isn't, it checks if the collision matches the LayerMask, and if it does, it makes the explosion and destroys the projectile:
void OnCollisionEnter(Collision other)
{
if (isHoming)
{
return;
}
if( && ((1<<other.gameObject.layer) & collisionLayers) != 0)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion,
gameObject.transform.position,
gameObject.transform.rotation) as GameObject;
//destroy the projectile
Destroy(gameObject);
}
}
Your question is a bit vague and doesn't look like you have put a lot of effort into understanding the code and trying to alterate it. Anyway I'll do my best.
always being able to fire (indifferent if the object is in range)`
probably simply set aimAssistRadius = 0; or entirely remove the check
if (Vector3.Distance(_target.Value.gameObject.transform.position, transform.position) > aimAssistRadius)
{
_target = null;
}
shoot towards the crosshair (to the screen midpoint) and NOT towards the object pivot point.
The script you posted (probably not yours) seems to have the entire purpose of doing what you not want to do: Aim assist. Removing it probably changes a lot of things but the simpliest would be to simply set the ProjectileScript._rigidbody.velocity in the moment the projectile is instantiated. Unfortunately you didn't provide the code where this happens.
I don't see in which moment your ShootComponent interacts with the ProjectileScript but probably in one of those UnityEvents ... ?
But in general it would maybe simply look like
public class ProjectileScript : MonoBehaviour
{
public float speed = 1.0f;
private RigidBody _rigidbody;
private void Awake()
{
_rigidbody = GetComponent<RigidBody>();
}
public void SetDirection(Vector3 direction)
{
_rigidbody.velocity = direction.normalized * speed;
}
}
and whereever you Instantiate the projectile do
var projectile = instantiatedObject.GetComponent<ProjectileScript>();
var direction = Camera.main.transform.forward;
projectile.SetDirection(direction);
as you can see you will have to make the
if (Vector3.Distance(transform.position, Target.position) < 1.0f)
{
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}
happen somewhere else since the code will not be target based anymore ... I would probably use OnCollisionEnter instead something like e.g.
private void OnCollisionEnter(Collision collision)
{
// maybe only collide with a certain tag
if(collision.gameObject.tag != "Target") return;
//make the explosion
GameObject ThisExplosion = Instantiate(Explosion, gameObject.transform.position, gameObject.transform.rotation) as GameObject;
//destory the projectile
Destroy(gameObject);
}

How to change player speed with public float from another script

Hey I am trying to change a float when my player collides with a object. I tried many ways of reference but only got null when trying to debug I came up with this so far. I want to get the gameobject that contains the player script meaning the player and after I want to get the component script tankmovement to change the variable in it.
Getting the null reference error in the powerups script line 79 reset function Tank=GameObject.FindWithTag("Player")
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour {
public bool boosting = false;
public GameObject effect;
public AudioSource clip;
public GameObject Tank;
private void Start()
{
Tank = GameObject.Find("Tank(Clone)");
TankMovement script = GetComponent<TankMovement>();
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!boosting)
{
clip.Play();
GameObject explosion = Instantiate(effect, transform.position, transform.rotation);
Destroy(explosion, 2);
GetComponent<MeshRenderer>().enabled = false;
GetComponent<Collider>().enabled = false;
Tank.GetComponent<TankMovement>().m_Speed = 20f;
//TankMovement.m_Speed = 20f;
boosting = true;
Debug.Log(boosting);
StartCoroutine(coolDown());
}
}
private IEnumerator coolDown()
{
if (boosting == true)
{
yield return new WaitForSeconds(4);
{
boosting = false;
GetComponent<MeshRenderer>().enabled = true;
GetComponent<Collider>().enabled = true;
Debug.Log(boosting);
// Destroy(gameObject);
}
}
}
void reset()
{
//TankMovement.m_Speed = 12f;
TankMovement collidedMovement = Tank.gameObject.GetComponent<TankMovement>();
collidedMovement.m_Speed = 12f;
//TankMovement1.m_Speed1 = 12f;
}
}
}
Trying to call on my m_Speed float in the player script to boost the speed of my player when he collides with it. How would you get a proper reference since my player is a prefab.
Tank script
using UnityEngine;
public class TankMovement : MonoBehaviour
{
public int m_PlayerNumber = 1;
public float m_Speed = 12f;
public float m_TurnSpeed = 180f;
public AudioSource m_MovementAudio;
public AudioClip m_EngineIdling;
public AudioClip m_EngineDriving;
public float m_PitchRange = 0.2f;
private string m_MovementAxisName;
private string m_TurnAxisName;
private Rigidbody m_Rigidbody;
private float m_MovementInputValue;
private float m_TurnInputValue;
private float m_OriginalPitch;
private void Awake()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
private void OnEnable ()
{
m_Rigidbody.isKinematic = false;
m_MovementInputValue = 0f;
m_TurnInputValue = 0f;
}
private void OnDisable ()
{
m_Rigidbody.isKinematic = true;
}
private void Start()
{
m_MovementAxisName = "Vertical" + m_PlayerNumber;
m_TurnAxisName = "Horizontal" + m_PlayerNumber;
m_OriginalPitch = m_MovementAudio.pitch;
}
private void Update()
{
// Store the player's input and make sure the audio for the engine is playing.
m_MovementInputValue = Input.GetAxis(m_MovementAxisName);
m_TurnInputValue = Input.GetAxis(m_TurnAxisName);
EngineAudio();
}
private void EngineAudio()
{
// Play the correct audio clip based on whether or not the tank is moving and what audio is currently playing.
if (Mathf.Abs(m_MovementInputValue) < 0.1f && Mathf.Abs(m_TurnInputValue) < 0.1f)
{
if (m_MovementAudio.clip == m_EngineDriving)
{
m_MovementAudio.clip = m_EngineIdling;
m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
m_MovementAudio.Play();
}
}
else
{
if (m_MovementAudio.clip == m_EngineIdling)
{
m_MovementAudio.clip = m_EngineDriving;
m_MovementAudio.pitch = Random.Range(m_OriginalPitch - m_PitchRange, m_OriginalPitch + m_PitchRange);
m_MovementAudio.Play();
}
}
}
private void FixedUpdate()
{
// Move and turn the tank.
Move();
Turn();
}
private void Move()
{
// Adjust the position of the tank based on the player's input.
Vector3 movement = transform.forward * m_MovementInputValue * m_Speed * Time.deltaTime;
m_Rigidbody.MovePosition(m_Rigidbody.position + movement);
}
private void Turn()
{
// Adjust the rotation of the tank based on the player's input.
float turn = m_TurnInputValue * m_TurnSpeed * Time.deltaTime;
Quaternion turnRotation = Quaternion.Euler(0f, turn, 0);
m_Rigidbody.MoveRotation(m_Rigidbody.rotation * turnRotation);
}
}
Since the TankMovement component you need to access is attached to the GameObject that is colliding with the power, you can get the TankMovement component you need to change by using other.gameObject.GetComponent<TankMovement>():
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Player"))
{
if (!boosting)
{
// stuff
TankMovement collidedMovement = other.gameObject.GetComponent<TankMovement>();
collidedMovement.m_Speed = 20f;
// more stuff
}
}
}

Categories

Resources