Search Unity

puzzling code

Discussion in 'Scripting' started by boolfone, Jun 29, 2016.

  1. boolfone

    boolfone

    Joined:
    Oct 2, 2014
    Posts:
    289
    I came across this code today:

    Code (CSharp):
    1. // Get the latest webcam shot from outside "Friday's" in Times Square
    2. using UnityEngine;
    3. using System.Collections;
    4.  
    5. public class ExampleClass : MonoBehaviour {
    6.     public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    7.     IEnumerator Start() {
    8.         WWW www = new WWW(url);
    9.         yield return www;
    10.         Renderer renderer = GetComponent<Renderer>();
    11.         renderer.material.mainTexture = www.texture;
    12.     }
    13. }

    It is from here:

    https://docs.unity3d.com/ScriptReference/WWW.html


    Can someone help me understand it? It seems to run automatically when attached to an object?

    I was aware of the “void Start(void)” which gets called automatically but was surprised to see this automatically called.

    Thanks.
     
  2. SteveJ

    SteveJ

    Joined:
    Mar 26, 2010
    Posts:
    3,085
  3. bigmisterb

    bigmisterb

    Joined:
    Nov 6, 2010
    Posts:
    4,221
    Here is some comments in that code about what it is doing.
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class ExampleClass : MonoBehaviour {
    5.     // the url to load
    6.     public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    7.    
    8.     // IEnumerators are things that can run outside of the
    9.     // normal Update/FixedUpdate process
    10.     // Start can be an IEnumerator, so it can run things and wait to load
    11.     IEnumerator Start() {
    12.         // create the WWW object and have it load the url from above
    13.         WWW www = new WWW(url);
    14.         // this waits until that has been loaded.
    15.         yield return www;
    16.        
    17.         // find the renderer of this object
    18.         Renderer renderer = GetComponent<Renderer>();
    19.         // apply the texture to the mainTexture portion of that material
    20.         renderer.material.mainTexture = www.texture;
    21.     }
    22. }
     
    Kurt-Dekker likes this.