0
\$\begingroup\$

I'm working on a small Unity 2D project in which I need to modify the collider of the player at runtime. I'm using Physics2D.Raycast to find the collider and then what I'd like to be able to do is then copy that exact collider over to the current gameObject and remove the current collider in the process. Basically when my Ray hits an object, I want my player to turn into that object.

I'm fairly new to Unity and have been digging through the API for some hints but haven't found anything yet. Any help would be appreciated.

So far all I have is as follows:

RaycastHit2D hit = Physics2D.Raycast(transform.position, lookDirection, Mathf.Infinity, 1 << 8);
        if (hit.collider != null)
        {

            //Change the collider somehow
            Collider2D myC = GetComponent<Collider2D>();
            myC = hit.collider; //Haha that doesn't work.

        }
\$\endgroup\$
  • \$\begingroup\$ can you provide a little bit more code? \$\endgroup\$ – Hamza Hasan Dec 29 '15 at 7:54
  • \$\begingroup\$ BTW Collider2D is an abstract class so it cannot be handled like this :) \$\endgroup\$ – Hamza Hasan Dec 29 '15 at 8:13
1
\$\begingroup\$

The answer to this really depends on exactly what you want to do. If you want the change to be permanent, you can destroy the current collider on your player and create a copy of the raycast target collider using reflection. Copying a component using reflection is covered in this answer on UnityAnswers http://answers.unity3d.com/questions/530178/how-to-get-a-component-from-an-object-and-add-it-t.html

If you only want the change to be temporary so that your player can change their form back, you could instead instantiate a copy of the raycast object with the position and rotation of your player and store it in a variable inside your player class. You could then disable the player's SpriteRenderer and Collider2D. This would make your player object invisible but would allow you to change your form back at any time by enabling the SpriteRenderer and Collider2D again.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.