so I been searching for hours on how to fix this problem but I couldn't find a solution so I wanted to ask here I have a walking particle VIDEO < ***as you can see in the video AFTER I walk 3 to 2 secs later the particles will
heres my code on my update I made it so it should check if we are moving to the right with the joystick then show it and if we are moving to the left with the joystick then it should show it as well but for some reason after that 2 to 3 secs the emittating wiill start[]
1
void Update()
{
if (joystick.Horizontal >= .2f)
{
hays.SetActive(true);
Instantiate(hays, particleposition.transform.position, hays.transform.rotation);
}
if (joystick.Horizontal <= -.2f)
{
hays.SetActive(true);
Instantiate(hays, particleposition.transform.position, hays.transform.rotation);
}
what I tried
I tried checking if its not doing the above code then it should just delete but it doesnt work at all it will still imitate I also tried checking the animation state but it still the same thing it wont stop imitating
if (joystick.Horizontal !>= .2f)
{
Destroy(gameObject, 1f);
}
if (joystick.Horizontal !<= -.2f)
{
Destroy(gameObject, 1f);
}
my full code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class partscript : MonoBehaviour
{
public Joystick joystick;
public GameObject hays;
public Rigidbody2D rb;
float horizontalMove = 0f;
public bool show = true;
public Animator animator2;
public Transform player;
public Transform particleposition;
// Start is called before the first frame update
void Start()
{
transform.position = particleposition.position;
animator2 = GetComponent<Animator>();
//Destroy(gameObject, 1f);
}
//destroy(hays);
// Update is called once per frame
void Update()
{
if (joystick.Horizontal >= .2f)
{
hays.SetActive(true);
Instantiate(hays, particleposition.transform.position, hays.transform.rotation);
}
if (joystick.Horizontal <= -.2f)
{
hays.SetActive(true);
Instantiate(hays, particleposition.transform.position, hays.transform.rotation);
}
if (joystick.Horizontal !>= .2f)
{
Destroy(gameObject, 1f);
}
if (joystick.Horizontal !<= -.2f)
{
Destroy(gameObject, 1f);
}
}
}
removed loop and changed the duration to 1 and it started to work
Related
Currently trying to move a sprite between two points and making it stop between those two points on mouseclick/tap. Cant figure out how to do that (Script isnt laying on the object that is being moved btw)
void Update() {
if(isMoving){
Vector3 v = startingPos;
v.x += distanceToCover * Mathf.Sin(Time.time * triangleSpeed);
transform.position = v;
}
if(Input.GetMouseButtonDown(1)){
}
}
If the first part of the code is working fine then just don't let the move be called meaning just set the isMoving to false.
void Update() {
if(isMoving){
Vector3 v = startingPos;
v.x += distanceToCover * Mathf.Sin(Time.time * triangleSpeed);
transform.position = v;
}
if(Input.GetMouseButtonDown(1)){
isMoving = false;
}
}
You could animate that movement and then set speed of animation to 0 when clicked
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class stoponclick : MonoBehaviour
{
public GameObject movingObject;
void Update()
{
if (Input.GetMouseButtonDown(1))
{
if (movingObject != null)
{
if (movingObject.GetComponent<Animator>()!=null)
{
movingObject.GetComponent<Animator>().speed=0;
}
}
}
}
}
I have been try for a while to stop the enemy rotate wen my player collide with it. I have insert a rigid body, and I have try to freeze position and also the freeze rotation but he keep doing the same, I can't find any were any info to learn about this problem.
I have google it a few times and could not find any thing, close to my problem.
This is the screenshot of the problem
https://imgur.com/fyryuqY
Also I have tried to set Angular drag to 0 but no success it keep doing the same.
It sounds like I am missing something, but I can't find any solution for it yet.
I have also tried to see all answers on unity forum but I can't find anywhere a solution or the way to learn about this problem.
I have edit to insert the enemy script
This is my enemy script
using UnityEngine;
using System.Collections;
public class target : MonoBehaviour {
public float health = 100f;
public Animator animx2;
public AudioSource audiovfx2;
public void TakeDamage (float amount)
{
health -= amount;
if (health <= 0f)
{
Die();
}
}
void Die()
{
animx2.SetBool("isdie",true);
audiovfx2.Play();
healthcontroller.score += 10;
health -= 10;
Destroy (gameObject, 1.5f);
}
void Update()
{
animx2 = GetComponent<Animator>();
GetComponent<AudioSource>().Play();
}
void OnTriggerEnter(Collider other) {
if (other.tag == "Player") {
Rigidbody rb = GetComponent<Rigidbody>();
rb.angularVelocity = Vector3.zero
//Stop Moving/Translating
//rbdy.velocity = Vector3.zero;
//Stop rotating
//rbdy.angularVelocity = Vector3.zero;
}
}
void OnTriggerExit(Collider other) {
if (other.tag == "Player") {
//here i want to return to normal
}
}
}
Thank you in advance
Did you try to nullify angularVelocity of the Rigidbody component, for example
rb.angularVelocity = Vector3.zero;
Here are the two Error messages I am receiving.
This seems to only happen when the Run animation is playing. Any help would be appreciated.
I am building this game for android and I am using mouse clicks to move the character. Since mouse clicks translate to touch events this should have no barring on the game as far as I know.
I guess I should also note that the animations play fine while playing the game.
'defaultModelfbx' AnimationEvent 'FootL' has no receiver! Are you missing a component?
'defaultModelfbx' AnimationEvent 'FootR' has no receiver! Are you missing a component?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class PlayerController : MonoBehaviour
{
float speed = 10;
float rotSpeed = 5;
Vector3 targetPosition;
Vector3 lookAtTarget;
Quaternion playerRot;
bool moving = false;
Animator thisAnim;
void Update()
{
thisAnim = GetComponent<Animator>();
// Get movement of the finger since last frame
if (Input.GetMouseButton(0))
{
SetTargetPosition();
}
if (moving)
{
Move();
}
}
void SetTargetPosition()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if(Physics.Raycast(ray, out hit, 1000))
{
targetPosition = hit.point;
lookAtTarget = new Vector3(targetPosition.x - `transform.position.x, 0, targetPosition.z - transform.position.z);`
playerRot = Quaternion.LookRotation(lookAtTarget);
moving = true;
}
}
void Move()
{
thisAnim.SetFloat("speed", 1);
transform.rotation = Quaternion.Slerp(transform.rotation, playerRot, rotSpeed * Time.deltaTime);
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed * Time.deltaTime);
if (transform.position == targetPosition)
{
moving = false;
thisAnim.SetFloat("speed", 0);
}
}
}
I had the same error, but with a different cause and solution.
All my code was in a (grand)parent gameobject (e.g. WerewolfPlayer) and I wanted to keep it this way. The animator was in a (grand)child gameobject (e.g. WEREWOLF_PBR) and it couldn't find the animation events:
To fix this, I bubbled-up the event from the child gameobject to the parent:
I edited the PlayerController.cs in the parent gameobject (e.g. WerewolfPlayer) to find the new "hand off animation events" script and fire the animation events when they happen:
using UnityEngine;
using System;
public class PlayerController : MonoBehaviour
{
private HandOffAnimationEvent handOffAnimationEvent;
// called when animation event fires
public void Pickup()
{
Debug.Log("player picks up object here...");
}
void OnEnable()
{
handOffAnimationEvent = GetComponentInChildren<HandOffAnimationEvent>();
handOffAnimationEvent.OnPickup += Pickup;
}
void OnDisable()
{
handOffAnimationEvent.OnPickup -= Pickup;
}
}
The new HandOffAnimationEvents.cs was added to the child gameobject (e.g. WEREWOLF_PBR) and when the animation event fires, it fires its own event:
using UnityEngine;
using System;
public class HandOffAnimationEvent : MonoBehaviour
{
public event Action OnPickup;
// This is the animation event, defined/called by animation
public void Pickup()
{
OnPickup?.Invoke();
}
}
Okay thanks to Nathalia Soragge I have found the solution to the problem.
If you look closely at the animation window you can see two white dashes at the top of the time line. I have clicked on one of them in the picture, and sure enough it is one of the events that were throwing the error message.
I am assuming I can just delete these two events since I do not have them anywhere in code. In this case it is looking for the events in my PlayerController since it is attached to my Model defaultModelfbx
UPDATE: I have deleted both events and now everything is running smoothly. Thanks again Nathalia!!!!!!! ;)
If you don't want to listen to any events, you can set Animator.fireEvents to false.
public Animator animator;
void Start()
{
animator.fireEvents = false;
}
https://docs.unity3d.com/ScriptReference/Animator-fireEvents.html
I had the same problem.I solved this by deleting all animation events and recreating all of them again.
Hi so what im trying to create is the player can right click on an enemy and he will follow at a certain distance. which is working fine. but what i want it to also do is stop at that distance too. currently if the enemy stops he will try and go to its exact position instead of stopping a little bit away this is what i have currently.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Attacking : MonoBehaviour {
NavMeshAgent agent;
Transform target;
public float distance;
public float followDistance;
// Use this for initialization
void Start () {
agent = GetComponent<NavMeshAgent>();
}
// Update is called once per frame
void Update () {
if (Input.GetMouseButton(0))
{
target = null;
}
if (Input.GetMouseButton(1))
{
RaycastHit hit;
if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit, 100))
{
if (hit.collider.gameObject.tag == "enemy" || hit.collider.gameObject.tag == "Player")
{
target = hit.collider.transform;
}
}
}
if(target != null)
{
distance = Vector3.Distance(transform.position, target.position);
if (followDistance <= distance)
agent.destination = target.position;
}
}
}
Attach a script to your enemy and give it a certain radius ,say 3f.
public float radius=3f;
for better understanding and visual aid use OnDrawGizmosSelected() (on your enemy script).
void OnDrawGizmosSelected ()
{
Gizmos.color=Color.yellow;
Gizmos.DrawWireSphere(transform.position,radius);
}
Now,on your player script use agent.StoppingDistance() as:
if(target != null)
{
distance = Vector3.Distance(transform.position, target.position);
if (followDistance <= distance){
agent.destination = target.position;
agent.StoppingDistance=target.radius;
}
}
Note:you will have to change target from transform to an instance of your player
i have a turret,as a game object when a enemy enters it's collison box,the turret starts firing towards it,the logic is when the enemy exits the collider,it should stop its firing ,and other problem is that when again an enemy enters the collison box i.e the second enemy,it gives me an exception ,"MissingReferenceException :the object of type 'transform' has been destroyed but you are still trying to access it.Your script should eihter be check if it is null or you should not destroy it",but i am checking if the list in not null in my code.here is my code
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class TurretScript : MonoBehaviour {
public float shotInterval = 0.2f; // interval between shots
public GameObject bulletPrefab; // drag the bullet prefab here
public float bulletSpeed;
private float shootTime = 0.0f;
private List<Transform> targets;
private Transform selectedTarget;
private Transform myTransform;
private Transform bulletSpawn;
void Start(){
targets = new List<Transform>();
selectedTarget = null;
myTransform = transform;
bulletSpawn = transform.Find ("bulletSpawn"); // only works if bulletSpawn is a turret child!
}
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "enemy"){ // only enemies are added to the target list!
targets.Add(other.transform);
}
}
void OnTriggerExit2D(Collider2D other){
if (other.tag == "enemy"){
targets.Remove(other.transform);
Debug.Log("gone out");
}
}
void TargetEnemy(){
if (selectedTarget == null){ // if target destroyed or not selected yet...
SortTargetsByDistance(); // select the closest one
if (targets.Count > 0) selectedTarget = targets[0];
}
}
void SortTargetsByDistance(){
targets.Sort(delegate(Transform t1, Transform t2){
return Vector3.Distance(t1.position, myTransform.position).CompareTo(Vector3.Distance(t2.position, myTransform.position));
});
}
void Update(){
TargetEnemy(); // update the selected target and look at it
if (selectedTarget)
{
// if there's any target in the range...
Vector3 dir = selectedTarget.position - transform.position;
float angle = Mathf.Atan2(dir.y,dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);// aim at it
if (Time.time >= shootTime){// if it's time to shoot...
// shoot in the target direction
Vector3 lookPos = new Vector3(bulletSpawn.position.x,bulletSpawn.position.y,0);
lookPos = lookPos - transform.position;
float ang = Mathf.Atan2(lookPos.y,lookPos.x)*Mathf.Rad2Deg;
GameObject b1 = Instantiate(bulletPrefab,new Vector3(transform.position.x,transform.position.y,5),transform.rotation)as GameObject;
b1.rigidbody2D.velocity = new Vector3(Mathf.Cos(ang*Mathf.Deg2Rad),Mathf.Sin(ang*Mathf.Deg2Rad),0)*bulletSpeed;
shootTime = Time.time + shotInterval; // set time for next shot
}
}
}
}
here is my enemy script
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class EnemyScript : MonoBehaviour {
public Transform target;
public float speed = 2f;
public int Health;
public float GetHealth()
{
return Health;
}
void Update ()
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
void TakeDamage(int damage){
Health -= damage;
if (Health <= 0)
Destroy(gameObject);
}
void OnTriggerEnter2D(Collider2D otherCollider)
{
PlayerControl shot = otherCollider.gameObject.GetComponent<PlayerControl>();
if (shot != null)
{
SpecialEffectsHelper.Instance.Explosion(transform.position);
Destroy(shot.gameObject);
}
}
}
you need to check if the selected target is the target leaving the collider. You remove the target from the targets list but the selectedTarget var is still populated.
For the null ref exception. Are you using Destroy() to kill the target? Destroy() doesn't cause an OnTriggerExit() or OnCollisionExit() event call, the object is just gone.
edit: you can get around the lack of a call by adding an OnDestroy() function to the dying object that sets it's position to something well outside the level/view of the player. This way the target leaves the collider and then disappears rather than just disappearing in place.