Search code examples
c#unity-game-enginecompiler-errorsparticle-system

Unity Particle system: Change Emitter Velocity with Script


I have a particle system connected with an object that it follows. The Emitter Velocity is here set on Rigidbody. What I want is to have the particle system follow the object, as it does, but when detecting a touch input the particles are to follow the touch input, changing the Emitter Velocity to Transform. When running the code that I attached, there are two compiler errors that I have tried and failed to fix. Would appreciate someone taking a look at it.

  • The 'Particle System' does not contain a definition for 'emitterVelocity' and no accessible extension method 'emitterVelocity' accepting a first argument of type 'ParticleSystem' could be found. line 28.
  • 'Transform' is a type, which is not valid in the given context. line 28.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragFingerMove : MonoBehaviour
{
    private Vector3 touchPosition;
    private ParticleSystem ps;
    private Vector3 direction;
    private float moveSpeed = 10f;

    // Use this for initialization
    private void Start()
    {
        ps = GetComponent<ParticleSystem>();
    }

    // Update is called once per frame
    private void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            touchPosition = Camera.main.ScreenToWorldPoint(touch.position);
            touchPosition.z = 0;
            direction = (touchPosition - transform.position);
            ps.emitterVelocity = Transform;
            ps.velocity = new Vector2(direction.x, direction.y) * moveSpeed;

            if (touch.phase == TouchPhase.Ended)
                ps.velocity = Vector2.zero;
        }
    }
}

Solution

  • First, when trying to access the Transform to which a Unity component is attached, you want to use transform (note lowercase "t" vs. uppercase). Switch Transform to transform or this.transform.

    transform is a property that all MonoBehaviours have that gives the same value as calling this.GetComponent<Transform>(). By contrast, Transform is the type UnityEngine.Transform, which is to say there exists a class with that name.

    Second, in regards to setting the emitter, you can set the emitterVelocityMode (labelled as "Emitter Velocity") in the particle system's main component. The values for emitterVelocityMode are an enum named "ParticleSystemEmitterVelocityMode".

    You can say:

    var ps_main = GetComponent<ParticleSystem>().main;
    ps_main.emitterVelocityMode = ParticleSystemEmitterVelocityMode.Transform;