Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Question SOLVED : 2D Gameobject never scales

Discussion in 'Scripting' started by rishikul030788, Sep 4, 2023.

  1. rishikul030788


    Jun 14, 2023

    I want to instantiate and scale an object (Trophy) when the player collides with a primary box type object.
    I could detect the collision with the box and instantiate the Trophy object but the Trophy object never scales. Here is my attempt to implement scaling-

    Code (CSharp):
    1. public class BoxBreak : MonoBehaviour
    2. {
    3.     [SerializeField]
    4.     private GameObject trophy;
    7.     // Start is called before the first frame update
    8.     void Start()
    9.     {
    11.         anim = GetComponent<Animator>();
    12.     }
    14.     // Update is called once per frame
    15.     void Update()
    16.     {
    18.     }
    20.     private void OnCollisionEnter2D(Collision2D collision)
    21.     {
    22.         if (collision.gameObject.CompareTag("Player"))
    23.         {
    24.             Debug.Log("collided with player");
    25.         }
    26.     }
    29.     private void OnTriggerEnter2D(Collider2D collision)
    30.     {
    31.         if ( == "Player")
    32.         {
    34.             anim.SetTrigger("BoxBreaking_animation");
    36.             Destroy(this.gameObject,1.8f);
    37.             GameObject localtrophy = Instantiate(trophy, new Vector2(transform.position.x, (transform.position.y) - 0.07f), Quaternion.identity);
    40.             Vector2 newScale = new Vector2(2.0f, 2.0f);
    42.             localtrophy.transform.localScale = newScale;
    44.             }
    49.             }
    53. }
  2. Indiana-Jonas


    Jul 24, 2015
    Do you perhaps have any script running on the trophy object itself or any animations?

    If you have animations that affect scale on the trophy that would conflict with this code.
  3. Killercarrot102


    Jun 20, 2022
    Try changing
    private GameObject trophy;
    public GameObject trophy;
    and setting trophy prefab from the editor then do
    trophy.transorm.scale = new vector3(put size here);
    in the on collision enter to scale it

    or you could put the trophy in the resources folder and in the start function write
    trophy = resorces.load<GameObject>("trophy");
    then scale it the same way
  4. wideeyenow_unity


    Oct 7, 2020
    this ^ ^..

    But creating a new object and modifying it's scale should work as intended.

    Code (CSharp):
    1. Destroy(this.gameObject,1.8f);
    2. GameObject localtrophy = Instantiate(trophy, new Vector2(transform.position.x, (transform.position.y) - 0.07f), Quaternion.identity);
    I would have destroy be called at the end, just for safety. I'm pretty sure the destroy logic doesn't kick in until the next frame anyway, so it should be ok? But just looks wrong..

    This is not needed, as just the reference to prefab is private, which means only this class can access it. So no issues there, as long as you have a proper reference.. Since you can actually instantiate one, then no problems exist.

    But it's probably because something in the throphy class is telling the new creation to be a standard size. If you want some type of animation, I would have that in trophy class, and just modify it's max size to animate through a function, or just a public variable.
  5. Kurt-Dekker


    Mar 16, 2013
    Do you have an animation on it?

    Animations always win (normally).

    If you are animating the scale property, stop it.

    Check also the "Write Defaults" property in the Animator states. It should be OFF
  6. rishikul030788


    Jun 14, 2023
    Thank you for your feedback !
    I am not running any animation for the Trophy sprite, nor any script. Here are the settings of trophy.
    Writes-default is set to off

    Attached Files:

    Last edited: Sep 4, 2023
  7. Kurt-Dekker


    Mar 16, 2013
    You're always going to have issues with the above ^ ^ ^ ^

    The proper way to set scales:

    NEVER set scale (or any part of scale) to zero or negative.

    NEVER use Vector2 because that makes the third term (Z) zero.

    ALWAYS use Vector3, and make sure that the .z is either 1.0f, or else your non-zero scale.

    Similarly never set scale to, especially in a UI, because this will cause layout divide-by-zeros and damage all your hierarchy.

    The above MUST be done.

    It may or may not fix your current issue.

    If it doesn't fix it then it is...

    Time to start debugging! Here is how you can begin your exciting new debugging adventures:

    You must find a way to get the information you need in order to reason about what the problem is.

    Once you understand what the problem is, you may begin to reason about a solution to the problem.

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is
    - you're getting an error or warning and you haven't noticed it in the console window

    To help gain more insight into your problem, I recommend liberally sprinkling
    statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the names of the GameObjects or Components involved?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also supply a second argument to Debug.Log() and when you click the message, it will highlight the object in scene, such as

    If your problem would benefit from in-scene or in-game visualization, Debug.DrawRay() or Debug.DrawLine() can help you visualize things like rays (used in raycasting) or distances.

    You can also call Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene manually, looking for all the parts, where they are, what scripts are on them, etc.

    You can also call GameObject.CreatePrimitive() to emplace debug-marker-ish objects in the scene at runtime.

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    Visit Google for how to see console output from builds. If you are running a mobile device you can also view the console output. Google for how on your particular mobile target, such as this answer for iOS: or this answer for Android:

    If you are working in VR, it might be useful to make your on onscreen log output, or integrate one from the asset store, so you can see what is happening as you operate your software.

    Another useful approach is to temporarily strip out everything besides what is necessary to prove your issue. This can simplify and isolate compounding effects of other items in your scene or prefab.

    If your problem is with OnCollision-type functions, print the name of what is passed in!

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    "When in doubt, print it out!(tm)" - Kurt Dekker (and many others)

    Note: the
    function is an alias for Debug.Log() provided by the MonoBehaviour class.
  8. wideeyenow_unity


    Oct 7, 2020
    what is that lock symbol next to scale in your screenshot? never seen that before
  9. MelvMay


    Unity Technologies

    May 24, 2013
    Uniform scale lock.
    wideeyenow_unity likes this.
  10. wideeyenow_unity


    Oct 7, 2020
    Ohh Kurt's got it, yeah scale is always a Vector3, even with 2D. nice catch!
  11. rishikul030788


    Jun 14, 2023

    Hi Kurt,

    Your comment just stuck with me...

    "- the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think"

    Finally to realize that there is this piece of code which with the intention of creating a scale up / down effect is the source of the problem. Taking it out led to the Trophy item scale. Thank you for the generous feedback.

    So now I know that my flawed logic was the problem, is there a way I could create a frame by frame scale up and scale down effect ?

    Here is my flawed code which effected the initial scale problem.

    Code (CSharp):
    2.     private float trophysizetimer=0f;
    3.     private float totaltimer=3f;
    4.     private float trophysize = 0.1f;
    6.          if (trophysizetimer <= totaltimer)
    7.                 {
    9.                     localtrophy.transform.localScale = new Vector2(1 + trophysize, 1 + trophysize);
    10.                     trophysizetimer = trophysizetimer + 0.2f;
    11.                 if (trophysizetimer > 1.9f)
    12.                     {
    13.                         localtrophy.transform.localScale = new Vector2(1 - trophysize, 1 - trophysize);
    14.                     }
    15.                     if (trophysizetimer == totaltimer)
    16.                     {
    17.                         localtrophy.transform.localScale = new Vector2(1, 1);
    18.                     }
    19.                 }
    My intent is that when the trophy instantiates , it should scale up to a certain extent defined by the timer variable and then scale down to its last scale.
    What I know is happening is that the code executes all in a single frame. I tried wrapping if statement in a while loop but that made things even worse and Unity crashed !

    Your insight would be really appreciated,

    Thank you...
  12. Kurt-Dekker


    Mar 16, 2013
    YUCKY! Don't write code for that... just make a one-time animation on the trophy and be done with it!

    That lets you even have an "after initial scale-up and scale down" idle animation too.

    If you have any questions about how the Animator / Animation system works, there's at least 57 billion tutorials already out on Youtube. Start there.

    Here's why:

    Unity will lock up 100% of the time EVERY millisecond your scripting code is running.

    Nothing will render, no input will be processed, no Debug.Log() will come out, no GameObjects or transforms will appear to update.

    Absolutely NOTHING will happen... until your code either:

    - returns from whatever function it is running

    - yields from whatever coroutine it is running

    As long as your code is looping, Unity isn't going to do even a single frame of change. Nothing.

    No exceptions.

    "Yield early, yield often, yield like your game depends on it... it does!" - Kurt Dekker
    rishikul030788 likes this.