Destroy particle system when initalised programmatically - c#

I have a game with a player and an enemy.
I also have a particle system for when the player dies, like an explosion.
I have made this particle system a prefab so I can use it multiple times per level as someone might die a lot.
So in my enemy.cs script, attached to my enemy, I have:
public GameObject deathParticle;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.name == "Player" && !player.dead){
player.dead = true;
Instantiate(deathParticle, player.transform.position, player.transform.rotation);
player.animator.SetTrigger("Death");
}
}
So this plays my particle system when the player gets killed by an enemy. Now on my player script, I have this. This specific function gets played after the death animation:
public void RespawnPlayer()
{
Rigidbody2D playerBody = GetComponent<Rigidbody2D>();
playerBody.transform.position = spawnLocation.transform.position;
dead = false;
animator.Play("Idle");
Enemy enemy = FindObjectOfType<Enemy>();
Destroy(enemy.deathParticle);
}
This respawns the player like normal but in my project each time I die I have a death (clone) object which I don't want. The last 2 lines are meant to delete this but it doesn't.
I have also tried this which didn't work:
Enemy enemy = FindObjectOfType<Enemy>();
ParticleSystem deathParticles = enemy.GetComponent<ParticleSystem>();
Destroy(deathParticles);

There is no need to Instantiate and Destroy the death particle, that will create a lot of overhead, you can simply replay it when you want it to start and stop it, when you dont need it
ParticleSystem deathParticleSystem;
private void OnTriggerEnter2D(Collider2D collision)
{
#rest of the code
deathParticleSystem.time = 0;
deathParticleSystem.Play();
}
public void RespawnPlayer()
{
//rest of the code
deathParticleSystem.Stop(true, ParticleSystemStopBehavior.StopEmittingAndClear);
}
or you can enable and disable the gameObject associated with your particle prefab
public GameObject deathParticlePrefab;
private void OnTriggerEnter2D(Collider2D collision)
{
#rest of the code
deathParticlePrefab.SetActive(true);
}
public void RespawnPlayer()
{
//rest of the code
deathParticlePrefab.SetActive(false);
}

You could always create a new script and assign it to the prefab that destroys it after a certain amount of time:
using UnityEngine;
using System.Collections;
public class destroyOverTime : MonoBehaviour {
public float lifeTime;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
lifeTime -= Time.deltaTime;
if(lifeTime <= 0f)
{
Destroy(gameObject);
}
}
}
So in this case you would assign this to your deathParticle. This script is useful in a multitude of scenarios if you're instantiating objects so that you don't have a load of unnecessary objects.

Related

Game object can't detect others when using collision.gameObject.tag in unity

I have designed a scenario as below:
I created an object spawner to collide with things tagged as "ob", using a boolean to manage the timing to spawn new obstacles. Nonetheless, after some testing, I found that it seemed like nothing had ever collided with one another(Judged by the strings I put in the if condition had never shown in the console.) Can't figure out why! Please HELP!!!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class newObSpawning : MonoBehaviour
{
public GameObject[] oblist;
private bool hasOb=true;
public float adjustSpawnx;
void Update()
{
if (!hasOb)
{
spawnObs();
hasOb = true;
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("ob"))
{
hasOb = true;
Debug.Log("hasOb"); //just for testing
}
}
private void OnTriggerExit2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("ob"))
{
hasOb = false;
Debug.Log("hasOb");
}
}
public void spawnObs()
{
int i = Random.Range(0, oblist.Length);
Debug.Log(i);
float y = 7.87f;
GameObject newob = Instantiate(oblist[i], new Vector3(transform.position.x+ adjustSpawnx,y,0), Quaternion.identity);
}
}
obspawner carry a "follow player" script to move at the same pace as the player,and it went just well
Your player doesn't seem to have a Rigidbody2D component. Add Rigidbody2D to your player. A collider can only emit OnTriggerEnter2D or OnTriggerExit2D events if there is a rigidbody on the object too
You have to tag the object "ob" that you want to register the collision with, most probably, I think what you are searching for is the collision of your player with object spawner so tag the player with "ob".

How do I make an instantiated object keep following my player after its instantiated?

I drew a little red animation thing for when my player gets hit. I have an arrow shooter in my level but my problem is the red damage effect instantiates where my player is at, but when my player moves the object stays in the player's old position. Like lets say my player is at x:10. The effect will spawn at x:10 but when I move to x:17 the effect will stay at x:10.
Here's my code
public int damagedealt;
public Player playerscript;
public GameObject RedDamage;
public Vector2 playerpos;
public GameObject player;
// Start is called before the first frame update
void Start()
{
playerscript = FindObjectOfType<Player>();
}
// Update is called once per frame
void Update()
{
playerpos = player.transform.position;
player = GameObject.FindGameObjectWithTag("Player");
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
playerscript.health -= damagedealt;
Instantiate(RedDamage, playerpos, transform.rotation);
Destroy(gameObject);
}
}
and if it's useful at all here's the damage effect script
{
public float duration;
// Start is called before the first frame update
void Start()
{
duration = .7f;
}
// Update is called once per frame
void Update()
{
duration -= Time.deltaTime;
if (duration <= .13f )
{
Destroy(gameObject);
}
}
}
You can either add a follow script to the object you would like to follow your player or you can child the object to the player. When an object is childed to another, its transform becomes relative to its parent. In your case, your instantiated object would move relative to your player.
As this seems like a temporary effect that is repeated multiple times, it might make sense to child an empty object for the sole purpose of spawning your effect there. Create an empty gameObject that is childed (meaning placed under in the scene hierarchy) to your player object. Make sure to set the position of this new empty object in a place where you would like to spawn your object.
Once you are happy with where the object is placed, you can alter your Instantiate slightly to fit the new approach.Instantiate has a few overloads to the method. The one I will use is as follows
public static Object Instantiate(Object original, Transform parent);
Instead of specifying a rotation, position, etc, you will specify the parent at which the object will be placed and childed to. Here is what the script would now look like
public int damagedealt;
public Player playerscript;
public GameObject RedDamage;
public Vector2 playerpos;
public GameObject player;
// serializing a field will expose it in the editor even if marked private
// while not allowing other scripts to access it
[SerializeField] private Transform DisplayDamageFeedback = null;
// Start is called before the first frame update
void Start()
{
playerscript = FindObjectOfType<Player>();
}
// Update is called once per frame
void Update()
{
playerpos = player.transform.position;
player = GameObject.FindGameObjectWithTag("Player");
transform.Translate(Vector2.right * speed * Time.deltaTime);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
playerscript.health -= damagedealt;
Instantiate(RedDamage, DisplayDamageFeedback);
Destroy(gameObject);
}
}
Make sure to assign the reference to DamageFeedback in the inspector to the empty gameObject you created earlier. If you need help on any of the steps just let me know.
Try something like this.
in the effects' 'Update' script:
GameObject player = GameObject.FindGameObjectWithTag("Player");;
public void MoveGameObject()
{
transform.position = new Vector3(player.transfom.position.x,player.transform.position.y,player.transform.position.z);
}
This means that every Update, the player object is found, and the effect's position is set to match the players.
See the following link for Unity's example of position:
https://docs.unity3d.com/ScriptReference/Transform-position.html

How to disable a script with void OnTriggerEnter2D?

So I have this script that disables my movement when I enter a certain area, how do I make my animation go from whatever animation they are in to my idle animation only when I enter the collider? Thanks!
using System.Collections.Generic;
using UnityEngine;
public class endLevel : MonoBehaviour
{
public void OnTriggerEnter2D(Collider2D collision)
{
GetComponent<CharacterController2d>().enabled = false;
Debug.Log("Level Cleared");
}
}
you have to specify that object is Player
first set your player Object Tag or Layer
set to "Player" and go to your script
if(collision.CompareTag("Player"))
or
int PlayerLayer;
void Start()
PlayerLayer = layer.NametoLayer("Player")
if(collision.gameObject.layer == PlayerLayer)
if collided gameObject is player. get player script's Animator to stop function.
collision.gameObject.GetComponent<Animator>().enabled = false;
"[...] make my animation go from whatever animation they are in to my idle animation only when I enter the collider[...]"
Use Animator.CrossFade. Example:
public void OnTriggerEnter2D(Collider2D collision)
{
GetComponent<Animator>().CrossFade("your_idle_state", 0.5f);
}
For performance reasons, I recommend caching the Animator reference in a private variable, initialized in Start(). If you are unsure if the object actually has an Animator Component, use TryGetComponent().

How to transform position from one object to the current player position?

So i have this little particlesystem attached on my player so if he dies he explodes. But i cant simply attach the particlesystem under the player because if i destroy my player the childs of the gameobjects get destroyed as well. The animation runs if he dies but not on his current spot so some ideas for that? Maybe to transform the position to the current position of the player while he dies?
Here my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerdeath : MonoBehaviour
{
public ParticleSystem death_explosion;
// Start is called before the first frame update
void Start()
{
death_explosion.Stop();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "deathcube")
Destroy(gameObject);
Debug.Log("collision detected");
death_explosion.Play();
}
}
What you could do is create a prefab of the particle object and reference it inside your script like so:
public ParticleSystem death_explosion_Prefab;
And instead of attaching it to the Player as a child, instantiate it on collision:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "deathcube")
{
Debug.Log("collision detected");
Instantiate(death_explosion_Prefab, gameObject.transform.position, Quaternion.identity);
Destroy(gameObject);
}
}
got it :) --> add death_explosion.transform.position = GameObject.Find("player").transform.position;

Unity Engine - Instantiate a prefab by collision

I have a GameObject called Player.
Attached to Player there is a script component called Player ( same )
Inside the Player's script, I have a field called _weaponPrefab ( GameObject type )
In the Inspector, I can easily drag & drop any prefabs from my Prefab folder, inside the _weaponPrefab variable.
All good so far. What I want to archive is: to be able to add my Prefabs based on a Collision2D. So if my Player collides with a Prefab, let's say a Sword, the prefab of that sword will be automatically attached and insert into the _weaponPrefab field inside the Player script.
Below my Player script:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float _speed = 5.0f;
[SerializeField] private float _fireRate = 0.2f;
private bool _canFire = true;
[SerializeField] private GameObject _weaponPrefab; <- to populate runtime
// Use this for initialization
void Start ()
{
transform.position = Vector3.zero;
}
// Update is called once per frame
void Update ()
{
if (Input.GetKeyDown(KeyCode.Space) && _canFire)
StartCoroutine(Shoot());
}
void OnTriggerEnter2D(Collider2D other)
{
//here i don't know how to continue.
}
public IEnumerator Shoot()
{
_canFire = false;
Instantiate(_weaponPrefab, transform.position + new Vector3(0, 1, 0), Quaternion.identity);
yield return new WaitForSeconds(_fireRate);
_canFire = true;
}
}
Edit: i just wrote a comment of where i don't know how to proceed.
There are many ways to accomplish what you desire.
My suggestion may be out of your comfort zone at first, but it will provide you with most flexibility and eventually easy of programming/ designing/ maintaining your game (in my opinion).
First make a scriptable object (what is a scriptable object and how do i use it?)
using UnityEngine;
using System.Collections;
using UnityEditor;
public class Item
{
[CreateAssetMenu(menuName = "new Item")]
public static void CreateMyAsset()
{
public GameObject prefab;
// you can add other variables here aswell, like cost, durability etc.
}
}
Create a new item (in Unity, Assets/new Item)
Then create a monobehaviour script which can hold the item. In your case let's name it "Pickup".
public class Pickup : MonoBehaviour
{
public Item item;
}
Finally in your player script, change your on TriggerEnter to:
void OnTriggerEnter2D(Collider2D other)
{
if(other.GetComponentInChildren<Pickup>())
{
var item = other.GetComponentInChildren<Pickup>().item;
_weaponPrefab = item.prefab;
}
}
When you instantiate a GameObject you need to pass basically 3 parameters (However not all of them are mandatory, check):
The prefab
The position
The rotation
Let's assume you have a placeholder in the hand or in the back of your character, to keep there the weapon once collected. This placeholder can be an empty gameobject (no prefab attached, but will have a transform.position component)
Now let's assume you have a list of weapons in the scene with their prefab and with a different tag each. Then you can do something like this:
GameObject weapon;
GameObject placeholder;
public Transform sword;
public Transform bow;
...
void OnTriggerEnter2D(Collider2D other)
{
//You can use a switch/case instead
if(other.gameObject.tag == "sword"){
Instantiate(sword, placeholder.transform.position, Quaternion.identity);
}else if(other.gameObject.tag == "bow"){
Instantiate(bow, placeholder.transform.position, Quaternion.identity);
}...
}
What I'll do is load the prefabs first in a Dictionary<string, GameObject> from the resources folder.
First I populate the dictionary with all the weapon prefabs in the Start method with the tag of the object as a key. Then in the OnTriggerEnter2D I check if the tag is in the dictionary then I instantiate it from there.
Take a look at the code :
private Dictionary<string, GameObject> prefabs;
// Use this for initialization
void Start () {
var sword = (GameObject) Resources.Load("Weapons/sword", typeof(GameObject));
prefabs.Add("sword", sword);
// Add other prefabs
};
void OnTriggerEnter2D(Collider2D other)
{
if (prefabs.ContainsKey(other.tag))
Instantiate(prefabs[other.tag]);
}
NOTE : your prefabs needs to be in the folder Assets/Resources/Weapons because I used Resources.Load("Weapons/sword", typeof(GameObject));

Categories