• 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
1
Question by Mikael1987 · Mar 17, 2012 at 02:26 PM · cameraarrays

Dynamic Camera and Array [SOLVED]

FIRST SCRIPT

public class CameraController : MonoBehaviour { public static ArrayList cameraNodes = new ArrayList(); public Transform player; private bool loopHandle = true; public int node;

 void Start ()
 {
     Vector3 vector = new Vector3();
     CameraNode camera = new CameraNode(0, vector);
     while (loopHandle)
     {
         if (cameraNodes.Count > 0)
         {
             for (int i = 0; i < cameraNodes.Count; i++)
             {
                 camera = (CameraNode)cameraNodes[i];
                 if (camera.range >= Vector3.Distance(player.position, camera.position))
                 {
                     node =i;

                 }
             }

         }
         camera = (CameraNode)cameraNodes[node];
         transform.position = camera.position;
         executeWait();
     }     
 }
 void Update ()
     {
     transform.LookAt(player);    
 }
 private void executeWait()
 {
     StartCoroutine(Wait(1));
 }
 private IEnumerator Wait(float seconds)
 {
     yield return new WaitForSeconds(seconds);
 }

}

public class CameraNode { public Vector3 position; public float range;

 public CameraNode(float range, Vector3 position)
 {
     this.position = position;
     this.range = range;
 }

}

What I'm trying to do with this code is dynamically change the main camera position to one of the "CameraNodes" when the character enters the range of each of them. I have different "emtpy game objects" with the 2nd script attached and the main camera with the first script attached to it,right now its actually crashing unity,I realize I have an infinity loop on the Start() function but it has a wait so it doesnt overloads the cpu. Any insight? Thanks in advanced.

SECOND SCRIPT

public class NodeController : MonoBehaviour {
    public float range;
    public static int numNodes=0;
    public int nodeNumber;
    void Start () {
        CameraNode myNode = new CameraNode(range, transform.position);
        CameraController.cameraNodes.Add(myNode);
        numNodes++;
        nodeNumber = numNodes;
    }    
}

Comment
Add comment · Show 1
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 PaxNemesis · Mar 17, 2012 at 02:42 PM 1
Share

That wait won't do you much good. You need to make start a coroutine and yield from there to make it have any effect. As it is now you just start a whole lot of wait coroutines.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by aldonaletto · Mar 17, 2012 at 04:01 PM

The variable loopHandle is never set to false, what makes the while infinite - and it's creating a Wait coroutine each iteration, what may produce thousands of Wait instances running at the same time, as @PaxNemesis said.
I would use a simpler and less CPU intensive approach: tag all nodes as "Node", find and save them at Start in a member variable nodes, create also a ranges array and fill it at Start with the node ranges, and finally find the nearest node and place the camera there. In Update, check if the player has exited the range - if so, find the nearest node and move the camera to its position.
That's the first script (attached to the camera):

public class CameraController : MonoBehaviour { public Transform player; // drag the player here public int curNode = 0;

 GameObject[] nodes; // will save the node objects here
 float[] ranges; // will save the ranges here

 void Start ()
 {
     nodes = GameObject.FindGameObjectsWithTag("Node"); // get all nodes
     ranges = new float[nodes.length]; // create the range array...
     for (int i = 0; i < nodes.length; i++){ // and fill it
         ranges[i] = nodes[i].GetComponent< NodeController>().range;
     }
     GotoNearestNode(); // place the camera at the nearest node
 }

 void Update ()
 {
     float dist = Vector3.Distance(player.position, nodes[curNode].transform.position);
     if (dist > ranges[curNode]){ // if player out of current range...
         GotoNearestNode(); // move camera to the nearest one
     }
     transform.LookAt(player); // aim the player
 }

 private void GotoNearestNode()
 {
     float dist = Mathf.Infinity;
     Vector3 pos = player.position;
     for (int i = 0; i < nodes.length; i++){
         float d = Vector3.Distance(pos, nodes[i].transform.position);
         if (d < dist){
             dist = d;
             curNode = i;
         }
     }
     // move the camera to the nearest node found
     transform.position = nodes[curNode].transform.position;
 }

} The node script would become very simple - just the range variable (remember to set the node tag to "Node"):

public class NodeController : MonoBehaviour {
    public float range; // set the range for each node object
}
NOTE: This is untested C# code written by a JS guy! It may contain logic errors, but more likely will produce lots of C# cryptic errors. Let me know if you have any problem.
Comment
Add comment · Show 5 · 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 Mikael1987 · Mar 17, 2012 at 04:48 PM 0
Share

That worked like a charm,only had to modify Transform array into a GameObject array since

 GameObject.FindGameObjectWithTag("node").transform.position;// THIS WOR$$anonymous$$S
 GameObject.FindGameObjectsWithTag("node").transform.position;// THIS DOESN'T

Anyways thanks a lot for the answers and the new "approach" to do it!.

avatar image Mikael1987 · Mar 17, 2012 at 05:41 PM 0
Share

Am I not doing that with? private void executeWait() { StartCoroutine(Wait(1)); } private IEnumerator Wait(float seconds) { yield return new WaitForSeconds(seconds); }

avatar image Mikael1987 · Mar 17, 2012 at 05:41 PM 0
Share

I do start at private void executeWait() { StartCoroutine(Wait(1)); } Not sure if thats what you meant?.

avatar image aldonaletto · Mar 17, 2012 at 06:16 PM 0
Share

The while should be in a coroutine: this way the yield would suspend it till the next frame. Since it was in a regular function, it was never suspended - and worse: each iteration started a new Wait coroutine, which would last until its 1 second interval had finished (God knows how many Wait functions would be active during this time!)

avatar image aldonaletto · Mar 17, 2012 at 06:21 PM 0
Share

You're right, it should be a GameObject array, since that's what FindGameObjectsWithTag returns - appending a .transform (worse yet, .Transform) to it definitely doesn't work... I edited the answer to fix this asha$$anonymous$$g error (it was a last $$anonymous$$ute change that I did to simplify things - but it screwed up the whole thing!)

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Cycle through an array? Have Camera Follow different Targets. 1 Answer

How to make camera position relative to a specific target. 1 Answer

Playing animation elements not working 2 Answers

How to add QR Scanner border? 0 Answers

Changing camera position to shoot through scope on gun 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