Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Bug (Need Help) Unsure why this works ... sometimes [Collision & Transforms]

Discussion in 'Physics' started by HmmDeveloped, Feb 29, 2024.

  1. HmmDeveloped

    HmmDeveloped

    Joined:
    Feb 29, 2024
    Posts:
    2
    Hey Everyone,

    I'm at an odd spot right now, Been trying to figure this out but can't seem to figure out why this script only works somtimes.

    The intention behind this script, is when an object (with a certain tag) stays within a collider and an input is pressed, the colliding object will set its postion & rotation to an already specified transform.

    Now this script works, sometimes, and I have no clue why it doesn't work all the time.

    I currently have this set up with 4 colliders attached to parent objects in the game scene, only 2 of these spots complete the transform BUT i've tested and it says it should be transforming the position in the other spots aswell, but it isnt. Very odd.

    I've been looking back and forth between the inspector and script and can't seem to find what is causing this, So I thought i'd reach out and see if anyone can spot any issues with my script (in case the problem is there).

    I'd appreciate any help that any could give!
    PlacementScript.PNG
     
  2. HmmDeveloped

    HmmDeveloped

    Joined:
    Feb 29, 2024
    Posts:
    2
    Update:
    I thought about component the script by removing it from the collider and placing it back on, Now it only works on 1 out of the 4 colliders I am using.
     
  3. Edy

    Edy

    Joined:
    Jun 3, 2010
    Posts:
    2,541
    OnTrigger methods might not be precise in all situations. I'd suggest to include OnTriggerEnter, with the same code as OnTriggerStay, and debug when the OnTrigger methods are invoked exactly. This might help you to better understand how the events report the different situations.

    As a side note, your code makes extensive use of FindObjectOfType every frame, which is a slow method. This is ok for quick prototyping, but will incur on significant performance issues when the project scales. A better and scalable approach is finding those objects once when the script starts (OnEnable) and store them in private variables. Then access them through these private variables, instead of finding the objects again every time.