Video Games Development

Unity3D – Access GameObjects and Components – CSharp

Unity3D – Access GameObjects and Components – CSharp

In Unity3D GameObjects are all entities in Unity scenes.

MAIN TOP MENU> GameObject>
– Particle System
– Camera
– GUI Text
– GUI Texture
– 3D Text
– Directional Light
– Point Light
– Spot Light
– Area Light
– Meshes
– etc…

To manage GameObjects in code you have to use the ‘gameObject’ base class.

In Unity3D Components are all ‘modifiers’ you can attach to a Gameobject.

MAIN TOP MENU> Components>
– Mesh
– Effects
– Physics
– Physics 2D
– Navigation
– etc…

Accessing this GameObject

1. Create a Cube, go to Inspector and add the script ‘DestroyBasic.cs’ as component.

DestroyBasic.cs:


using UnityEngine;
using System.Collections;

public class DestroyBasic : MonoBehaviour
{
    void Update ()
    {
        if(Input.GetKey(KeyCode.Space))
        {
            Destroy(gameObject); // notice the keyword gameObject
        }
    }
}

Play, press Space to destroy it.

Notice: ‘Destroy(gameObject)’, you can use simple the keyword ‘gameObject’ and Unity3D will destroy the game object attached to the script.

Accessing this Component

1. Create a Cube, go to Inspector and add the scripts:
– ‘OtherScript.cs’ as component
– ‘example.cs’ as component

example.cs:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Update() {
        // first declare the variable otherScript of type OtherScrip and store the component 'GetComponent'
        // type variablename = get <scriptname>
        OtherScript otherScript = GetComponent<OtherScript>();
        otherScript.DoSomething(); // manipulate the component
    }
}

Accessing Other GameObjects – Inspector assignable references

If you set a varible as ‘public’ you can assign it in Inspector, even while you are playing!


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // scope type variablename
    public Transform target; // Setup in Inspector
    void Update() {
        target.Translate(0, 1, 0);
    }
}

Below you can drag a Gameobject that contains the ‘OtherScript’ on the target slot in the inspector.


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // scope type variablename
    public OtherScript target; // Drag and Drop in Inspector a Gameobject with the script 'OtherScript' 
    void Update() {
        target.foo = 2;              // using OtherScript variables
        target.DoSomething("Hello"); // usibg OtherScript functions
    }
}

Located through the object hierarchy

1. Create the hierarchy:

Forearm (parent)
– Hand (child)

Attach to Forearm example.cs:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        transform.Find("Hand").Translate(0, 1, 0); // find childs with name
    }
}

Once you have found the transform in the hierarchy, you can use GetComponent to get to other scripts.


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        transform.Find("Hand").GetComponent<OtherScript>().foo = 2;
        transform.Find("Hand").GetComponent<OtherScript>().DoSomething("Hello");
        transform.Find("Hand").rigidbody.AddForce(0, 10, 0);
    }
}

You can loop over all children:


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Example() {
        foreach (Transform child in transform) {
            child.Translate(0, 10, 0);
        }
    }
}

Located by name


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Start() {
        // type varname = find the gameobject SomeGuy
        GameObject go = GameObject.Find("SomeGuy"); // find in Project window the object with name 'SomeGuy'
        // manipulate SomeGuy 
        go.transform.Translate(0, 1, 0);

        GameObject player = GameObject.FindWithTag("Player");
        player.transform.Translate(0, 1, 0);
    }
}

Located by tag

To assign a tag go to Inspector> Tag> Add Tag


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    void Start() {
        // type varname = find a gameobject with tag Player
        GameObject player = GameObject.FindWithTag("Player");
        // get from Player the component OtherScript
        player.GetComponent<OtherScript>().DoSomething();
    }
}

Passed as parameters


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // se il trigger entra in contatto con altri oggetti
    void OnTriggerStay(Collider other) {
        // se gli altri oggetti hanno un rigidbody
        if (other.rigidbody)
            // aggiungi una forza
            other.rigidbody.AddForce(0, 2, 0);
        
    }
}


using UnityEngine;
using System.Collections;

public class example : MonoBehaviour {
    // se il trigger entra in contatto con altri oggetti
    void OnTriggerStay(Collider other) {
        // se gli altri componenti hanno lo script OtherScript
        if (other.GetComponent<OtherScript>())
            // ottieni OtherScript e fai qualcosa
            other.GetComponent<OtherScript>().DoSomething();
        
    }
}

All scripts of one Type

Find any object of one class or script name.

FindObjectOfType


// Search object of class GUITexture

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void Start() {
        GUITexture texture = FindObjectOfType(typeof(GUITexture));
        if (texture)
            Debug.Log("GUITexture object found: " + texture.name);
        else
            Debug.Log("No GUITexture object could be found");
    }
}  

FindObjectsOfType

Il precedente era singolare ‘FindObjectOfType’, questo è plurale ‘FindObjectsOfType’


// When clicking on the object, it will disable all springs on all 
// hinges in the scene

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    void OnMouseDown() {
        HingeJoint[] hinges = FindObjectsOfType(typeof(HingeJoint)) as HingeJoint[];
        foreach (HingeJoint hinge in hinges) {
            hinge.useSpring = false;
        }
    }
}

My website: http://www.lucedigitale.com

Ref: http://docs.unity3d.com/412/Documentation/ScriptReference/index.Accessing_Other_Game_Objects.html

By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Access GameObjects and Components – CSharp

Unity3D – Physics – OnMouseDown – Disable all Springs in Scene

Unity3D – Physics – OnMouseDown – Disable all Springs in Scene

// When clicking on the object, it will disable all springs on all 
// hinges in the scene

    function OnMouseDown () {
        var hinges : HingeJoint[] = FindObjectsOfType(HingeJoint) as HingeJoint[];
        for (var hinge : HingeJoint in hinges) {
            hinge.useSpring = false;
        }
    }
By |Unity3D, Video Games Development|Commenti disabilitati su Unity3D – Physics – OnMouseDown – Disable all Springs in Scene

CSharp – Properties – get-set

CSharp – Properties – get-set

Properties allow you to control the accessibility of a classes variables.
A property consists of 2 parts, a get and a set method, wrapped inside the property.
Only one method is required, this allows you to define read-only and write-only properties.

Syntax:

...

// la proprietà è la stringa Color
public string Color
{
    // get restituisce il valore di una variabile
    get { return color; }

    // set assegna a color il valore  - keyword value - proveniente dall'esterno 
    set { color = value; }
}
...

Example:


// definisco la proprietà Color come pubblica e di tipo stringa
public string Color
{
    get 
    {
        return color.ToUpper(); // converte una stringa in caratteri maiuscoli
    }
    set 
    { 
        if(value == "Red")
            color = value; // keyword value assegna il valore proveniente dall'esterno a color
        else
            Console.WriteLine("This car can only be red!");
    }
}

For italian people: come funziona?
1. if(value == “Red”) -> se la variabile è uguale a ‘Red’ -> set -> color = Red
2. get -> ritorna ‘RED’

Example:


class TimePeriod
{
    private double seconds;

    // proprietà - double Hours -
    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}


class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}
// Output: Time in hours: 24

For italian people: come funziona?
1. si avvia Main()
2. dichiato ‘t’ come variabile di tipo TimePeriod, la sintassi è la stessa che uso per richiamare una funzione
3. t.Hours = 24; -> assegnare un valore a ‘Hours’ causa l’avvio di ‘set’ che memorizza i dati in secondi
4. restituisce ‘get’ -> restituisce i dati in ore
5. System.Console.WriteLine(“Time in hours: ” + t.Hours); -> t.Hours è quello restituito da get

Example:


// Declare a Code property of type string:
public string Code
{
   get
   {
      return code;
   }
   set
   {
      code = value;
   }
}

// Declare a Name property of type string:
public string Name
{
   get
   {
     return name;
   }
   set
   {
     name = value;
   }
}

// Declare a Age property of type int:
public int Age
{ 
   get
   {
      return age;
   }
   set
   {
      age = value;
   }
}

Working Example:


using System;
namespace tutorialspoint
{
   class Student
   {

      private string code = "N.A";
      private string name = "not known";
      private int age = 0;

      // Declare a Code property of type string:
      public string Code
      {
         get
         {
            return code;
         }
         set
         {
            code = value;
         }
      }
   
      // Declare a Name property of type string:
      public string Name
      {
         get
         {
            return name;
         }
         set
         {
            name = value;
         }
      }

      // Declare a Age property of type int:
      public int Age
      {
         get
         {
            return age;
         }
         set
         {
            age = value;
         }
      }
      public override string ToString()
      {
         return "Code = " + Code +", Name = " + Name + ", Age = " + Age;
      }
    }
    class ExampleDemo
    {
      public static void Main()
      {
         // Create a new Student object:
         Student s = new Student();
            
         // Setting code, name and the age of the student
         s.Code = "001";
         s.Name = "Zara";
         s.Age = 9;
         Console.WriteLine("Student Info: {0}", s);
         //let us increase age
         s.Age += 1;
         Console.WriteLine("Student Info: {0}", s);
         Console.ReadKey();
       }
   }
}

The result is:

Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10

For italian people: come funziona?
1. si avvia per prima Main()
2. Student s = new Student(); -> dichiaro l’oggetto s di tipo Student()
3. s.Code = “001”; -> avvia ‘class Studen’t> proprietà ‘Code’> set> code=001
4. get -> ritorna il valore code=001, quindi al di fuori di ‘class Student’ la proprietà Code=001

Ref: http://www.tutorialspoint.com/csharp/csharp_properties.htm

By |CSharp|Commenti disabilitati su CSharp – Properties – get-set

CSharp – Namespace

CSharp – Namespace

Defining a namespace

Con la keyword ‘namespace’ possiamo definire un set di ‘nomi’ riservati ad un determinato scopo comune.
All’interno di un ‘namespace’ ci posso essere classi, funzioni e variabili.

Syntax:

...
// Define a namespace
namespace namespace_name
{
   // code declarations
}
....
// Call a namespace
namespace_name.item_name;
...

Example:


using System;
namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}   
class TestClass
{
   static void Main(string[] args)
   {
      // dichiaro fc di tipo classe namespace_cl() prelevata dal namespace first_space
      first_space.namespace_cl fc = new first_space.namespace_cl();
      // dichiaro sc di tipo classe namespace_cl() prelevata dal namespace second_space
      second_space.namespace_cl sc = new second_space.namespace_cl();
      // avvia le funzioni prelevate dal namespace first_space
      fc.func();
      // avvia le funzioni prelevate dal namespace second_space
      sc.func();
      // aspetto che l'utente interagisca con la tastiera prima di chiudere la finestra
      Console.ReadKey();
   }
}

The result is:

Inside first_space
Inside second_space

using

Con la keyword ‘using’ indichiamo al compilatore che il codice che scriveremo userà i ‘nomi’ specificati nel ‘namespace’ indicato.
In questo modo siamo in grado di scrivere codice più compatto.

In C# lo utilizziamo nelle applicazioni console per indicare al compilatore che utilizziamo il namespace ‘using System;’ fornito da Microsoft.

using System;
Console.WriteLine ("Hello there");

è equivalente a:

System.Console.WriteLine("Hello there");

Vediamo un esempio con un namespace creato da noi:


using System;
using first_space;
using second_space;

namespace first_space
{
   class abc
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}
namespace second_space
{
   class efg
   {
      public void func()
      {
         Console.WriteLine("Inside second_space");
      }
   }
}   
class TestClass
{
   static void Main(string[] args)
   {
      abc fc = new abc();
      efg sc = new efg();
      fc.func();
      sc.func();
      Console.ReadKey();
   }
}

The result is:

Inside first_space
Inside second_space

Notare come è stato sufficiente scrivere:

abc fc = new abc(); // dichiaro che fc è tipo classe abc
fc.func(); // richiamo la funzione

invece di:

first_space.namespace_cl fc = new first_space.namespace_cl();
fc.func();

Molto più breve e merno soggetto a errori di battitura.

By |CSharp|Commenti disabilitati su CSharp – Namespace

CSharp – Static Polymorphism – Operator Overloading

CSharp – Static Polymorphism – Operator Overloading

Polymorphism is a Greek word that means “many-shaped”
Overloaded operators are functions with special names the keyword ‘operator’ followed by the symbol for the operator being defined.

Syntax:

...
public static Box operator+ (Box b, Box c)
....

Notice: ‘operator+’ keyword

Example:


using System;

namespace ConsoleApplication1
{

    class Box
    {
        private double length;      // Length of a box
        private double breadth;     // Breadth of a box
        private double height;      // Height of a box

        public double getVolume()
        {
            return length * breadth * height;
        }
        public void setLength(double len)
        {
            length = len;
        }

        public void setBreadth(double bre)
        {
            breadth = bre;
        }

        public void setHeight(double hei)
        {
            height = hei;
        }
        // Overload + operator to add two Box objects.
        public static Box operator +(Box b, Box c)
        {
            Box box = new Box();
            box.length = b.length + c.length;
            box.breadth = b.breadth + c.breadth;
            box.height = b.height + c.height;
            return box;
        }

    }

    class Tester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();         // Declare Box1 of type Box
            Box Box2 = new Box();         // Declare Box2 of type Box
            Box Box3 = new Box();         // Declare Box3 of type Box
            double volume = 0.0;          // Store the volume of a box here

            // box 1 specification
            Box1.setLength(6.0);
            Box1.setBreadth(7.0);
            Box1.setHeight(5.0);

            // box 2 specification
            Box2.setLength(12.0);
            Box2.setBreadth(13.0);
            Box2.setHeight(10.0);

            // volume of box 1
            volume = Box1.getVolume();
            Console.WriteLine("Volume of Box1 : {0}", volume);

            // volume of box 2
            volume = Box2.getVolume();
            Console.WriteLine("Volume of Box2 : {0}", volume);

            // Add two object as follows:
            Box3 = Box1 + Box2;

            // volume of box 3
            volume = Box3.getVolume();
            Console.WriteLine("Volume of Box3 : {0}", volume);
            Console.ReadKey();
        }
    }

}

The result is:

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

For italian people: come funziona?

1. Viene eseguita prima Main()
2. Box Box1 = new Box(); -> dichiaro le variabili come appartenenti al tipo classe ‘Box’
3. Box1.setLength(6.0); -> invio alla classe ‘Box’ funzione ‘setLenght’ il valore 6.0 -> che viene assegnato a ‘length’
4. Idem come sopra per tutte le specifiche di Box1′ e ‘Box2’
5. public static Box operator +(Box b, Box c) … return box; -> Overload dell’operatore, vengono computati separatamente Box1′ e ‘Box2’
6. volume = Box1.getVolume(); -> avvia dalla classe ‘Box’ la funzione ‘getVolume()’ e calcola il volume

Se togliamo le righe…


      // Overload + operator to add two Box objects.
      public static Box operator+ (Box b, Box c)
      {
         Box box = new Box();
         box.length = b.length + c.length;
         box.breadth = b.breadth + c.breadth;
         box.height = b.height + c.height;
         return box;
      }

verrà restituito un errore di compilazione.

By |CSharp|Commenti disabilitati su CSharp – Static Polymorphism – Operator Overloading