Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Holobyte · Aug 12, 2014 at 10:26 PM · c#move an objectscene change

Is there a better method to programatically move offscreen objects?

Hey,

I'm creating a 2D vertical endless runner as my first game. I've wrote a script to place 5 wall prefabs at each side of the screen and 3 background prefabs. The camera follows the player vertically (with some dampening) and so when a prefab enters and then leaves the screen, it's moved above the highest prefab:

 public class SceneBuilder : MonoBehaviour
 {
 
     public Transform lWall;
     public Transform rWall;
     public Transform bg;
 
     private IList<Entry> lWalls = new List<Entry>();
     private IList<Entry> rWalls = new List<Entry>();
     private IList<Entry> bgs = new List<Entry>();
     private float wallDistance = 3.75f;
 
     void Awake()
     {
         for (int y = -2; y <= 2; y++)
         {
             lWalls.Add(new Entry { Prefab = (Transform)Instantiate(lWall, new Vector3(-wallDistance, y * lWall.localScale.y, 0.5f), Quaternion.identity) });
             rWalls.Add(new Entry { Prefab = (Transform)Instantiate(rWall, new Vector3(wallDistance, y * rWall.localScale.y, 0.5f), Quaternion.identity) });
             if (y > -2 && y < 2)
             {
                 bgs.Add(new Entry { Prefab = (Transform)Instantiate(bg, new Vector3(0, y * bg.localScale.y, 3f), Quaternion.identity) });
             }
         }
     }
 
     void Update()
     {
         new List<IList<Entry>>() { lWalls, rWalls, bgs }.ForEach(CheckVisibility);
     }
 
     private void CheckVisibility(IList<Entry> entries)
     {
         foreach (var entry in entries)
         {
             if (!entry.BeenVisible && entry.Prefab.renderer.isVisible) 
             {
                 entry.BeenVisible = true; 
             }
 
             if (!entry.WentInvisible && entry.BeenVisible && !entry.Prefab.renderer.isVisible)
             {
                 entry.WentInvisible = true;
             }
         }
 
         if (entries.Any(p => p.WentInvisible))
         {
             var entry = entries.Where(p => p.WentInvisible).OrderBy(p => p.Prefab.transform.position.y).First();
             entry.BeenVisible = false;
             entry.WentInvisible = false;
             MovePrefab(entry.Prefab, entries.OrderByDescending(p => p.Prefab.transform.position.y).First().Prefab.transform.position.y);
         }
     }
 
     private void MovePrefab(Transform prefab, float maxPos)
     {
         var height = prefab.transform.localScale.y;
         if (height == 3)
         {
             prefab.transform.position = new Vector3(prefab.transform.position.x, maxPos + 3, prefab.transform.position.z);
         }
         else
         {
             prefab.transform.position = new Vector3(prefab.transform.position.x, maxPos + 8, prefab.transform.position.z);
         }
     }
 
     private class Entry
     {
         public Transform Prefab { get; set; }
         public bool BeenVisible { get; set; }
         public bool WentInvisible { get; set; }
     }
 }

I want to know if there's a better way to achieve the same results that I'm not aware of. I'm experienced with C# but I'm learning Unity's API as I go so I could have missed something that would make things easier/optimal.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image IvovdMarel · Aug 12, 2014 at 10:40 PM 0
Share

Rather than creating a new list in the Update function and iterating through, it'd be way more readable & efficient to place the visibility logic code in the Entry class itself.

Wouldnt have to create, reorder (twice) your list every frame

avatar image Holobyte · Aug 13, 2014 at 11:01 AM 0
Share

Yeah, I changed the way I implemented the code but kept that silly iteration ins$$anonymous$$d of simply calling the function directly. It's fixed now.

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Kiwasi · Aug 13, 2014 at 12:02 AM

A couple of alternative methods to consider.

  • Place a trigger just offscreen. When the GameObject hits the trigger then move them. (OnTriggerEnter)

  • Use transform.position to figure out when an object is offscreen and move

Creating new lists every frame is going to kill you from a GC perspective. In many cases its more efficient to repopulate an existing list.

Here's an example of a script that might do the job. Use this by placing on each GameObject that is part of the background. You can set the public variables via the inspector or via code.

 public float lowerLimit;
 public float distanceToMoveUp;
 
 void Update (){
     if(transform.position.y < lowerLimit){
         transform.position = new Vector3 (transform.position.x, transform.position.y + distanceToMoveUp, transform.position.z);
     }
 }
Comment
Add comment · Show 3 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Holobyte · Aug 13, 2014 at 09:02 AM 0
Share

I thought of the trigger method but I'm not sure how "just offscreen" would work on different screen proportions. I guess it's a matter of trying those different aspect ratios and adjusting accordingly.

And thanks for the List tip, it was a really dumb way to make three simple function calls.

avatar image Kiwasi · Aug 13, 2014 at 09:24 AM 0
Share

Just off screen can be a fair distance, if you need to compensate for different screen sizes

I do hope you hang around. While we have several users who are experienced Unity developers, we don't have many that are experienced with C# first.

Worth pointing out that Unity doesn't include the full C# library, there are a few random things not supported. The other key difference is that Unity developers tend to take all sorts of shortcuts and aproximations. Getting the job done fast is better then getting the job done right.

avatar image Holobyte · Aug 13, 2014 at 11:03 AM 0
Share

You bet I'll stick around, this is a great comunity and Unity is a lovely tool. I've implemented the trigger and the code feels smoother now. Thanks for your inputs.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Help with elevator Script 2 Answers

Joystick movement Android 2D 0 Answers

Help using Lerp inside of a coroutine. 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges