hi everyone I made a tank that shoot sphere balls on mouse click.
my C# script:
GameObject prefab;
// Use this for initialization
void Start () {
prefab = Resources.Load("projectile") as GameObject;
}
// Update is called once per frame
void Update() {
if (Input.GetMouseButtonDown(0))
{
GameObject Orb = Instantiate(prefab) as GameObject;
Orb.transform.position = transform.position + Camera.main.transform.forward * 2;
Rigidbody rb = Orb.GetComponent<Rigidbody>();
rb.velocity = Camera.main.transform.forward * 40;
}
}
but i want to shoot a particle that i created. how can I do that? I trying change my scripts but this didnt work.
Once you instantiate your effect prefab to a clone game object in your game, you need to get the particle system component. In many cases, instantiate any prefab in Update() is a bad idea (destroying game object repeatedly can potentially cause memory leak), instead just do it either on Awake, Start or Enable.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FireParticlesOnMouseDown : MonoBehaviour {
public Transform effectPrefab;
public Camera mainCamera;
private Transform _clone;
private ParticleSystem _clone_ps;
private ParticleSystem.EmissionModule _clone_ps_em;
void OnEnable () {
//"Camera.main" is pricey, use it only when you run out of options.
if (!mainCamera) {
mainCamera = Camera.main;
}
_clone = Instantiate(effectPrefab);
_clone.parent = transform;
_clone.localPosition = Vector3.forward * 2f;
_clone.localRotation = Quaternion.identity;
_clone_ps = _clone.GetComponent<ParticleSystem>();
_clone_ps.Play();
_clone_ps_em = _clone_ps.emission;
_clone_ps_em.enabled = false;
}
void Update () {
if (Input.GetMouseButton(0)) {
_clone_ps_em.enabled = true;
//Calling ps.Play during Update will cause the effect to reset itself repeatedly.
} else {
_clone_ps_em.enabled = false;
}
}
}