I have been working to create mouse-based movement for my Unity3D game. I have gotten the movement, but I am having trouble setting of a variable for move speed that I can modify using a skill. This is my first attempt at using C# and I am very inexperienced. This is the beginnings of a long project, so any help or advice would be greatly appreciated.
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.AI;
namespace EO.ARPGInput
{
[RequireComponent(typeof(NavMeshAgent))]
public class PlayerController : MonoBehaviour
{
public Vector3 velocity;
[SerializeField] private InputAction movement = new InputAction();
[SerializeField] public LayerMask layerMask = new LayerMask();
private NavMeshAgent agent = null;
private Camera cam = null;
private void Start()
{
cam = Camera.main;
agent = GetComponent<NavMeshAgent>();
}
private void OnEnable()
{
movement.Enable();
}
private void OnDisable()
{
movement.Disable();
}
private void Update()
{
HandleInput();
}
public void HandleInput()
{
if (movement.ReadValue<float>() == 1)
{
Ray ray = cam.ScreenPointToRay(Mouse.current.position.ReadValue());
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100, layerMask))
{
PlayerMove(hit.point);
}
}
}
public void PlayerMove(Vector3 location)
{
agent.SetDestination(location);
}
}
}
Sometimes Unity docs have all the answers you need. NavMeshAgent-Speed
Try using agent.speed. create a global integer "public int sp=1;" above and then in Start or in Update do
agent.speed=sp;
Then once it is working you can just change that integer's value in whatever method you want. Good luck
Related
I've written a simple short code using agent.destination from the NavMesh Agent that allows enemies to track players. However, in the process of chasing the target, the enemy keeps slipping and not chasing properly.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
using static UnityEngine.EventSystems.EventTrigger;
public class Enemy : MonoBehaviour
{
public Transform target;
public Transform runAwayPos;
public NavMeshAgent agent;
public Transform spwanPosition;
void Start()
{
agent = GetComponent<NavMeshAgent>();
}
void Update()
{
StartCoroutine(Run());
if (Time.timeScale == 0)
{
transform.position = spwanPosition.position;
}
}
IEnumerator Run()
{
agent.speed = 9f;
agent.destination = target.transform.position;
yield return null;
}
private void OnTriggerEnter(Collider collision)
{
if (collision.gameObject.CompareTag("Player"))
{
transform.position = spwanPosition.position;
Debug.Log("hit");
}
}
}
I wonder how the enemy can track a player without slipping.
First of all, you call IEnumarator per frame. this causes unwanted consequences.Use either update or IEnumarator.
In my opininon,
void Update()
{
agent.SetDestination(target.position);
if (Time.timeScale == 0)
{
transform.position = spwanPosition.position;
}
}
By the way, you should use a boolean to check the untracked case.
I am tring to follow this tutorial https://www.youtube.com/watch?v=gmaAK_BXC4c to make a vr gun but I am getting an the following error:
'XRBaseInteractable' does not contain a definition for 'onSelectEntering' and no accessible extension method 'onSelectEntering' accepting a first argument of type 'XRBaseInteractable' could be found (are you missing a using directive or an assembly reference?) [Assembly-CSharp]csharp(CS1061)
for the following lines :
socketInteractor.onSelectEntering.AddListener(AddMagazine);
socketInteractor.onSelectExiting.AddListener(RemoveMagazine);
Here is my code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.Interaction.Toolkit;
[AddComponentMenu("Nokobot/Modern Guns/Simple Shoot")]
public class SimpleShoot : MonoBehaviour
{
[Header("Prefab Refrences")]
public GameObject bulletPrefab;
public GameObject casingPrefab;
public GameObject muzzleFlashPrefab;
[Header("Location Refrences")]
[SerializeField] private Animator gunAnimator;
[SerializeField] private Transform barrelLocation;
[SerializeField] private Transform casingExitLocation;
[Header("Settings")]
[Tooltip("Specify time to destory the casing object")] [SerializeField] private float destroyTimer = 2f;
[Tooltip("Bullet Speed")] [SerializeField] private float shotPower = 500f;
[Tooltip("Casing Ejection Speed")] [SerializeField] private float ejectPower = 150f;
public AudioSource source;
public AudioClip fireSound;
public AudioClip reload;
public Magazine magazine;
public AudioClip noAmmo;
public XRBaseInteractable socketInteractor;
public void AddMagazine(XRBaseInteractable interactable)
{
magazine = interactable.GetComponent<Magazine>();
source.PlayOneShot(reload);
}
public void RemoveMagazine(XRBaseInteractable interactable)
{
magazine = null;
}
public void Slide()
{
}
void Start()
{
if (barrelLocation == null)
barrelLocation = transform;
if (gunAnimator == null)
gunAnimator = GetComponentInChildren<Animator>();
socketInteractor.onSelectEntering.AddListener(AddMagazine);
socketInteractor.onSelectExiting.AddListener(RemoveMagazine);
}
public void PullTheTrigger()
{
if(magazine && magazine.numberOfBullet > 0)
{
gunAnimator.SetTrigger("Fire");
}
else
{
source.PlayOneShot(noAmmo);
}
}
//This function creates the bullet behavior
void Shoot()
{
magazine.numberOfBullet--;
source.PlayOneShot(fireSound);
if (muzzleFlashPrefab)
{
//Create the muzzle flash
GameObject tempFlash;
tempFlash = Instantiate(muzzleFlashPrefab, barrelLocation.position, barrelLocation.rotation);
//Destroy the muzzle flash effect
Destroy(tempFlash, destroyTimer);
}
//cancels if there's no bullet prefeb
if (!bulletPrefab)
{ return; }
// Create a bullet and add force on it in direction of the barrel
Instantiate(bulletPrefab, barrelLocation.position, barrelLocation.rotation).GetComponent<Rigidbody>().AddForce(barrelLocation.forward * shotPower);
}
//This function creates a casing at the ejection slot
void CasingRelease()
{
//Cancels function if ejection slot hasn't been set or there's no casing
if (!casingExitLocation || !casingPrefab)
{ return; }
//Create the casing
GameObject tempCasing;
tempCasing = Instantiate(casingPrefab, casingExitLocation.position, casingExitLocation.rotation) as GameObject;
//Add force on casing to push it out
tempCasing.GetComponent<Rigidbody>().AddExplosionForce(Random.Range(ejectPower * 0.7f, ejectPower), (casingExitLocation.position - casingExitLocation.right * 0.3f - casingExitLocation.up * 0.6f), 1f);
//Add torque to make casing spin in random direction
tempCasing.GetComponent<Rigidbody>().AddTorque(new Vector3(0, Random.Range(100f, 500f), Random.Range(100f, 1000f)), ForceMode.Impulse);
//Destroy casing after X seconds
Destroy(tempCasing, destroyTimer);
}
}
So I'm currently trying to add my player object with it's script into my camera script that is written for camera object.
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
private float damping = 0.2f;
public bool canMove = true;
public PlayerMovement player;
private void Start()
{
player = gameObject.GetComponent<PlayerMovement>();
}
void FixedUpdate()
{
if (player.faceRight)
{
offset = new Vector3(1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
else if (!player.faceRight)
{
offset = new Vector3(-1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
}
}
My problem is that I can't write player = gameObject.Find("Player"); because unity is saying something like "those are different types of elements" but I can drag my player object if I write public PlayerMovement player; and it works. The thing is I want to learn how to use that without dragging my object.
First of all you can expose and assign private (and protected) fields via the Inspector by using the attribute [SerializeField] without being forced to make them public like e.g.
[SerializeField] private PlayerMovement player;
private void Awake()
{
// if it's not referenced via the Inspector
// get it from this object on runtime as fallback
if(!player) player = GetComponent<PlayerMovement>();
}
And then, well, your field player is of type PlayerMovement while Find returns a GameObject → Not the same type.
Now if you want to get that component from the same object this script is attached to .. then why should you use the expensive Find at all?! You already know the object! Use only GetComponent to get the component attached tot he same object as this script (just like in the code above).
If you really want to use Find then you want to use GetComponent on the result, not on gameObject which is the reference to that scripts own GameObject. You would rather do
[SerializeField] private PlayerMovement player;
private void Awake()
{
if(!player) player = GameObject.Find("player").GetComponent<PlayerMovement>();
}
or if there is anyway only one instance of that type in your scene you can also simply use FindObjectOfType
[SerializeField] private PlayerMovement player;
private void Awake()
{
if(!player) player = FindObjectOfType<PlayerMovement>();
}
In general: If you can reference something via the Inspector it is always better doing so. It is way more efficient because the reference will be serialized into your scene or prefab asset so when it is loaded you already "know" the target reference. Using Find is very expensive and even though it was optimized a lot in later versions also GetComponent is work you could be avoiding ;)
I added my both GameObject and PlayerMovement attributes. Wrote gameObject first, which is called as "Player". Then by using my GameObject, I interacted with my script which is called PlayerMovement.
using UnityEngine;
public class CameraController : MonoBehaviour
{
public Transform target;
private Vector3 offset;
private float damping = 0.2f;
public bool canMove = true;
private GameObject playerObject;
private PlayerMovement playerMovementScript;
private void Start()
{
player = GameObject.Find("Player");
player = gameObject.GetComponent<PlayerMovement>();
}
void FixedUpdate()
{
if (player.faceRight)
{
offset = new Vector3(1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
else if (!player.faceRight)
{
offset = new Vector3(-1f, 0.5f, -10f);
transform.position = Vector3.Lerp(transform.position, target.position, damping) + offset;
}
}
}
I fixed that problem when I was writing that issue here. So I'm kinda proud of myself but also I want to share my solution so if anyone encounter a problem like this, they can fix their problems. If anyone has better solution please share.
At the moment I am programming a Unity 2D game. When the game is running the cars start moving and respawn continuously. I added kind of a life system to enable the possibility to shoot the cars. My issue is that my health bar as well as my score board need references to the objects they refer to, but I am unable to create a reference to an object which is not existing before the game starts. Another issue is that I don't know how to add a canvas to a prefab in order to spawn it with the cars continuously and connect them to the car. Is there a way to avoid these conflicts or how is it possible to set the references into prefabs. I will add the code of the spawner, the car and the the scoreboard. Already thank you in advance
Spawner:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawner : MonoBehaviour
{
public GameObject carPrefab;
public GameObject enemyCarPrefab;
public GameObject kugel;
public float respawnTime = 10.0f;
public int counterPlayer1=0;
public int counterPlayer2=0;
public int counterEnergy=0;
// Use this for initialization
void Start () {
StartCoroutine(carWave());
}
private void spawnPlayerCars(){
GameObject a = Instantiate(carPrefab) as GameObject;
a.transform.position = new Vector2(-855f, -312.9426f);
counterPlayer1++;
}
private void SpawnEnemyCars(){
GameObject b = Instantiate(enemyCarPrefab) as GameObject;
b.transform.position = new Vector2(853,-233);
counterPlayer2++;
}
private void SpawnEnergy(){
GameObject c = Instantiate(kugel) as GameObject;
c.transform.position = new Vector2(-995,-192);
counterEnergy++;
}
IEnumerator carWave(){
while(true){
yield return new WaitForSeconds(respawnTime);
if(counterPlayer1<3){
spawnPlayerCars();
Debug.Log(counterPlayer1);
}
if(counterPlayer2<3){
SpawnEnemyCars();
Debug.Log(counterPlayer2);
}
if(counterEnergy<3){
SpawnEnergy();
}
}
}
}
Car:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyCar : MonoBehaviour
{
public float speed = 3f;
int zählerAuto1=0;
private Vector2 screenBounds;
public AnzeigePunktzahlPlayer2 points;
public Spawner sp;
public int maxHealth=100;
public int currentHealth;
public HealthBar healthbar;
void Start () {
screenBounds = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, Screen.height));
points= GetComponent<AnzeigePunktzahlPlayer2>();
sp= GetComponent<Spawner>();
currentHealth=maxHealth;
healthbar.SetMaxHealth(maxHealth);
}
void Update()
{
Vector2 pos = transform.position;
if(pos.x>-855f){
pos = transform.position;
pos.x-= speed* Time.deltaTime;
transform.position=pos;
zählerAuto1++;
}else{
points.counter++;
Debug.Log(points.counter);
sp.counterPlayer2--;
Debug.Log(sp.counterPlayer2);
Destroy(this.gameObject);
}
}
private void OnCollisionEnter2D(Collision2D other) {
if (other.collider.tag=="Kugel"){
takeDamage(40);
//sp.counterPlayer2--;
if(currentHealth<=0)
{
Destroy(this.gameObject);
}
}
}
public void takeDamage(int damage){
currentHealth-= damage;
healthbar.SetHealth(currentHealth);
}
public void getHealed(int heal){
currentHealth+= heal;
healthbar.SetHealth(currentHealth);
}
}
Scoreboard(one part of it(the other one is almost the same)):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class AnzeigePunktzahlPlayer1 : MonoBehaviour
{
public int counter;
public TextMeshProUGUI textPlayer1;
void Start()
{
// counter=0;
textPlayer1= GetComponent<TextMeshProUGUI>();
}
// Update is called once per frame
void Update()
{
textPlayer1.SetText( counter.ToString());
}
}
You could make the health bars and the canvas children of the Car prefab and have them spawn together.
I am trying to do a 2d game and my object doesn't affect the player's lifebar after they collide. The player's healthbar will will get a bigger lifetime but I think something it's wrong with the scripts. (Also the collider of object that needs to be destroy is "is trigger" checked). I put this PowerUp on the object, and the character script and healthbar script on the player.
Character.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
public class Character : MonoBehaviour
{
Rigidbody2D rb;
float dirX;
[SerializeField]
float moveSpeed = 5f, jumpForce = 600f, bulletSpeed = 500f;
Vector3 localScale;
public Transform barrel;
public Rigidbody2D bullet;
// Use this for initialization
void Start()
{
localScale = transform.localScale;
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
dirX = CrossPlatformInputManager.GetAxis("Horizontal");
if (CrossPlatformInputManager.GetButtonDown("Jump"))
Jump();
if (CrossPlatformInputManager.GetButtonDown("Fire1"))
Fire();
}
void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, rb.velocity.y);
}
void Jump()
{
if (rb.velocity.y == 0)
rb.AddForce(Vector2.up * jumpForce);
}
void Fire()
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
HealthBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider slider;
public Gradient gradient;
public Image fill;
public float health = 100;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
fill.color = gradient.Evaluate(1f);
}
public void SetHealth(int health)
{
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
PowerUp.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PowerUp : MonoBehaviour
{
public float multiplayer = 1.4f;
public GameObject pickupEffect;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Pickup(other);
}
}
void Pickup(Collider player)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
HealthBar stats =player.GetComponent<HealthBar>();
stats.health *= multiplayer;
// Remove Effect
Destroy(gameObject);
}
}
First of all as others already mentioned for a 2D game with Rigidbody2D and (hopefully) Collider2D components you want to use OnTriggerEnter2D instead!
The Physics and Physics2D are two completely separated engines and don't know each other. A 3D OnTriggerEnter will never get called for 2D physics events like collisions etc.
Then note that
Also the collider of object that needs to be destroy is "is trigger" checked
this is exactly the wrong way round. If your object shall track a OnTriggerEnter then the one that enters (the player) should have isTrigger enabled! In most cases you don't want to do this because the player shall e.g. actually collide with the floor and not fall through it etc.
So what you would need is rather putting an additional script on the player itself that waits for other trigger objects to enter!
Then to be sure either debug your code line by line or add additional logs in order to see what happens:
PowerUp
// put this on the pickup item
public class PowerUp : MonoBehaviour
{
// Make these private, nobody else needs access to those
// (Encapsulation)
[SerializeField] private float multiplayer = 1.4f;
[SerializeField] private GameObject pickupEffect;
public void Pickup(HealthBar stats)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
stats.health *= multiplayer;
// Remove Effect
Destroy(gameObject);
}
}
PowerUpDetector (on the player)
// put on player!
public class PowerUpDetector : MonoBehaviour
{
// reference this via the Inspector
[SerializeField] private HealthBar healthbar;
private void Awake()
{
if(!healthBar) healthBar = GetComponent<HealthBar>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("PowerUp"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var powerup = other.GetComponent<PowerUp>();
if(!powerup)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
powerup.Pickup(healthbar);
}
}
Well, and then what you do is only changing the float value
stats.health *= multiplayer;
but you never update the GUI accordingly like you would do when instead using
stats.SetHealth(stats.health * multiplayer)
(Btw: I think you mean multiplier ;) )
I would suggest to rather implement a property like e.g.
public class HealthBar : MonoBehaviour
{
// Make these private, nobody else needs access to those
// (Encapsulation)
[SerializeField] private Slider slider;
[SerializeField] private Gradient gradient;
[SerializeField] private Image fill;
[SerializeField] private float health = 100;
public float Health
{
get { return health; }
set
{
health = value;
slider.value = health;
fill.color = gradient.Evaluate(slider.normalizedValue);
}
}
// be careful with variable names if you have this name already
// for a class field .. was ok this time but might get confusing
public void SetMaxHealth(int value)
{
slider.maxValue = value;
// The property handles the rest anyway
Health = value;
}
}
so now instead of calling SetHealth you simply assign a new value to Health and its setter is automatically execute as well so your GUI is updated.
public void Pickup(HealthBar stats)
{
//Spawn a cool effect
Instantiate(pickupEffect, transform.position, transform.rotation);
//Apply effect to the player
stats.Health *= multiplayer;
Destroy(gameObject);
}
Your qustions are below,
player will get a bigger lifetime
Also the collider of object that needs to be destroy
What situation possibly you could have
Check your Character is Triggered, so it calls 'OnTriggerEnter' and also check tag.
Check your powerUp item that checked true as trigger, 'isTrigger'
Check if collider or hit object scale is tiny, it won't work with collider.
If you have nothing with above check-list, then it should be working