Reputation: 59
I want to instantiate the particle system when clicking the coins in my game but the Particle System is not appearing at the same place where my coins are.
I used this code, I don't know where to specify the position of a Particle System in the same place where I am clicking (mouse position) or where the coins are. I used prefab for my coins and tagged them. and also pickupeffect clone is created when I click the coin so I need to destroy them after few seconds
void Update ()
{
if (Input.GetMouseButtonDown (0)) {
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint
(Input.mousePosition), Vector2.zero);
}
if (hit.collider != null) {
if (hit.collider.tag == "coin") {
Instantiate (Resources.Load ("Pickupeffect"));
Destroy (hit.collider.gameObject);
}
}
}
Upvotes: 1
Views: 2288
Reputation: 146
Hope it can help you
private Gameobject ObjectThatYouNeedToDestroy;// gameobject initialization
void Update () {
if (Input.GetMouseButtonDown (0)) {
RaycastHit2D hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
}
if (hit.collider != null)
So, when the clicked object is a coin, then :
if (hit.collider.tag == "coin") {
Instantiate the object at the position of object that is being hit by cursor (hit.transform.position
) with default prefab rotation (Quaternion.identity
).
Instantiate (Resources.Load ("Pickupeffect"), hit.transform.position, Quaternion.identity);//instantiate particle prefab in coin position with original prefab rotation
float DelayTime = 5f;// change delay with any value
Assign the hit object to variable ObjectThatYouNeedToDestroy
, in case that the value hit.transform.gameobject
can't be assessed in another function.
ObjectThatYouNeedToDestroy= hit.transform.gameobject;// assign coin that clicked as ObjectThatYouNeedToDestroy
The last step is to execute DelayedDestroy
function after delay time expires.
Invoke ("DelayedDestroy", DelayTime);//execute function with delay
}
}
this is the function that destroy gameobject named ObjectThatYouNeedToDestroy
(coin)
void DelayedDestroy(){
Destroy (ObjectThatYouNeedToDestroy);
}
Upvotes: 0
Reputation: 1748
You can get the hit.collider.gameObject
position and instantiate your system in the same position after you destroy the coin. Have in mind that if the coin inherits a position different than x=0, y=0
you may want to instantiate the object and set the same parent. The code should like this:
if (hit.collider.tag == "coin") {
ReplaceCoinWithSys(hit.collider.gameObject, Resources.Load ("Pickupeffect"))
}
and the method should be like this:
private void ReplaceCoinWithSys(GameObject coin, GameObject system){
Instantiate(system,new Vector2 (coin.transform.position.x, coin.transform.position.y), Quaternion.identity);
Destroy (coin);
}
I hope this helps, hit me up when you complete your game I want to try it out :)
Upvotes: 1