Search Unity

Question How to add a Particle System to a prefab

Discussion in 'Prefabs' started by Blejz43, Apr 5, 2021.

  1. Blejz43

    Blejz43

    Joined:
    Mar 4, 2020
    Posts:
    8
    Hello, i have prefab that spawns on Start and follows the player. the player game object has a particle system that works perfectly. I tried to do the same thing for the prefab, but it wont work. I want it to have particles while the prefab exists. I cant find any similar threads for my problem.
    Thanks for any response.

    Here is the code for the prefab:


    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class enemyfollow : MonoBehaviour
    {

    public float speed;
    private Transform target;
    public Rigidbody2D rb2;

    public ParticleSystem ps1;

    // Start is called before the first frame update
    void Start()
    {
    target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();

    GetComponent<Rigidbody2D>();
    GetComponent<ParticleSystem>();

    }

    // Update is called once per frame
    void Update()
    {

    transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
    rb2.velocity = Vector2.zero;

    partikels();
    }

    void partikels()
    {

    ps1.Play();
    }
    }
     
  2. sand_lantern

    sand_lantern

    Joined:
    Sep 15, 2017
    Posts:
    210
    If you're trying to do it through the editor, make sure you actually have it attached in your prefab.

    Otherwise, you never assigned ps1 to your particle system. In your start function you need to say something like this if you're trying to get it programmatically:

    Code (CSharp):
    1. ps1 = GetComponent<ParticleSystem>();
    As a side note, there's really no point to the GetComponent<RigidBody>() in your Start. Also, you shouldn't be setting the transform position like you are in Update if your object has a rigidbody. See https://docs.unity3d.com/ScriptReference/Rigidbody-position.html

    You will probably want a private variable to store your RigidBody component on.