Why mySpriteRenderer = GetComponent <SpriteRenderer>(); was not used?

I took the lecture as a challenge before watching it. When I tried to solve the challenge how to flip the sprite my first thought was to write

mySpriteRenderer = GetComponent(); in the Start() and then use mySpriteRenderer.transform.localScale = new Vector2 … in FlipSprite().

I copied this practice from how myRigidBody object (is this the right word?) was created.

This seems to work but as this is different from the example used in the lesson there must be a reason why not to do it like this. Could you please tell what is the reason for not doing it this way?

Hi Hirmu,

Did you test your idea? Does it work? If so, it’s a solution. :slight_smile:

Given your code worked, you had the right idea and basically the same solution. At least, you are accessing the same Transform object. All components have got a transform property which refers to the Transform object of the game object to which the component is attached.

Your SpriteRenderer is attached to the same game object as “this” script component. For this reason, mySpriteRenderer.transform is equal transform. mySpriteRenderer could be removed because it makes the code longer but it is not wrong to do it this way.

Is this what you wanted to know?


See also:

Ok, I see. Thanks for the answer.

Why there is a need to create a myRigidbody object (again, sorry if this is a wrong word) and the properties cannot be changed directly?

What do you mean by recreate again? Do you have an example?

In C#, we have to distinguish between variables and objects. We see variables but we do not see objects.

This topic was automatically closed 20 days after the last reply. New replies are no longer allowed.

Privacy & Terms