Search code examples
unity-game-enginepositionsystemparticles

Unity 2D transform particle system


I'm trying to figure out how position an explosion created with the Unity particle system. The explosion should happen where a bomb collides with a box collider. I am not having much luck with the C# script. Any advice is appreciated. Code snippet listed below. xPos and yPos are declared as floats.

   // This part works.
    xPos = collisionObject.transform.position.x;
    yPos = collisionObject.transform.position.y;

    // This part generates an error.
    explosionContainer.transform.position.x = xPos;
    explosionContainer.transform.position.y = ypos;

Solution

  • Explanation

    This happens because Transform.position is a property of type Vector3 which is a struct. Structures in C# is a value types. What happens here:

    1. Since structs are value types collisionObject.transform.position returns you a copy of some Vector3
    2. By doing .x = xPos you are trying to modify x member of this copy of some Vector3 struct. This copy is going to be discarded instantly. Thus your assignment is useless. This is why compiler gives you an error.

    Solution

    If you want assign a new value to Transform.position you need to do it as follows:

    Vector3 newPosition = new Vector3(xPos, yPos);
    explosionContainer.transform.position = newPosition;
    

    Alternatively, you can use Transform.Translate method as Daniel has pointed out.