Alternative method to colouring sprites

If you want to use more than one colour or if you change the colour of the “Package” the method Rick uses requires you have multiple variables for each package colour and then manually change each variable and object to reflect. This is code you can use to only change each “Package” colour and have it reflect without doing anything else.

bool hasPackage;
[SerializeField]float timeDelay = 1;
Color32 noPackageColour;
SpriteRenderer spriteRenderer;

void Start()
{
spriteRenderer = GetComponent();
noPackageColour = spriteRenderer.color; // I use this as to get the colour of the Car directly
}

void OnTriggerEnter2D(Collider2D collision)
{
if (collision.tag == “Package” && !hasPackage)
{
Debug.Log(“Picked Up”);
hasPackage = true;
// The same method used to get the Car’s colour can be used to get the “Package” colour
// and then assign it directly to the car
spriteRenderer.color = collision.GetComponent().color;
Destroy(collision.gameObject, timeDelay);
}
else if (collision.tag == “Customer” && hasPackage)
{
Debug.Log(“Delivered”);
spriteRenderer.color = noPackageColour;
hasPackage = false;
}
}

1 Like

I tried this line to get the color of the package and change the color of the car
spriteRenderer.color = collision.GetComponent().color;
and I got this error message
‘Collision’ does not contain a definition for ‘GetComponent’ [Assembly-CSharp]

Could please kindly you share the full section of code that you use it in?
The only possible solutions I can think of with that error is that you’d need to use collision.gameObject.GetComponent().color; Possible reason is the difference in the version of unity that is being used

Here is my very similar solution:

    private void OnTriggerEnter2D(Collider2D other)
    {
        if (other.tag == "Package" && !hasPackage)
        {
            Debug.Log(other.name + " picked up!");
            hasPackage = true;
            Destroy(other.gameObject, destroyDelay);

            SpriteRenderer packageRenderer = other.GetComponent<SpriteRenderer>();
            spriteRenderer.color = packageRenderer.color;
        }
        if (other.tag == "Customer" && hasPackage)
        {
            Debug.Log(other.name + " received package!");
            hasPackage = false;
            spriteRenderer.color = noPackageColor;
        }
    }

I’m guessing the angle brackets are needed and possibly not showing due to markdown in the comments editor.

1 Like

Yea, this is why we encourage people to use the code blocks to display code

Privacy & Terms