This page has been translated automatically.
UnigineEditor
Interface Overview
Assets Workflow
Settings and Preferences
Working With Projects
Adjusting Node Parameters
Setting Up Materials
Setting Up Properties
Landscape Tool
Using Editor Tools for Specific Tasks
Extending Editor Functionality
Программирование
Fundamentals
Setting Up Development Environment
Usage Examples
UnigineScript
C++
C#
UUSL (Unified UNIGINE Shader Language)
File Formats
Rebuilding the Engine Tools
GUI
Double Precision Coordinates
API
Containers
Common Functionality
Controls-Related Classes
Engine-Related Classes
Filesystem Functionality
GUI-Related Classes
Math Functionality
Node-Related Classes
Objects-Related Classes
Networking Functionality
Pathfinding-Related Classes
Physics-Related Classes
Plugins-Related Classes
IG Plugin
CIGIConnector Plugin
Rendering-Related Classes
Внимание! Эта версия документация УСТАРЕЛА, поскольку относится к более ранней версии SDK! Пожалуйста, переключитесь на самую актуальную документацию для последней версии SDK.
Внимание! Эта версия документации описывает устаревшую версию SDK, которая больше не поддерживается! Пожалуйста, обновитесь до последней версии SDK.

Migrating to UNIGINE from Unity: Programming

Game logic in a Unity project is implemented via Script components. You got used to determine GameObject's behavior by writing event functions like Start(), Update(), etc.

UNIGINE has quite a similar concept, which can be easily adopted — C# Component System, which is safe and secure and ensures high performance. Logic is written in C# components that can be assigned to any node in the scene. Each component has a set of functions (Init(), Update(), etc.), that are called by the corresponding functions of the Engine's main loop.

Programming in UNIGINE using C# is not much different from programming in Unity software. For example, let's compare how rotation is performed in Unity software:

Source code (C#)
using UnityEngine;

public class MyComponent : MonoBehaviour
{
    public float speed = 90.0f;

    void Update()
    {
        transform.Rotate(0, speed * Time.deltaTime, 0, Space.Self);
    }
}

and in UNIGINE:

Source code (C#)
using Unigine;

public class MyComponent : Component
{
	public float speed = 90.0f;
	
	void Update()
	{
		node.Rotate(0, 0, speed * Game.IFps);
	}
}

The Run button is available in the Editor to run an instance of the application in a separate window. Along with the button, there are settings available to fine-tune run options.

That's how we'll make the wheel rotate using C# Component System and run an instance to immediately check it:


Moreover in UNIGINE, you can also implement Application Logic for the whole application by writing code in the AppWorldLogic.cs, AppSystemLogic.cs and AppEditorLogic.cs files stored in the source/ project folder.

To learn more about the execution sequence and how to build components, follow the links below:

For those who prefer C++, UNIGINE allows creating C++ applications using C++ API and, if required, C++ Component System.

Writing Gameplay Code#

Printing to Console#

Unity software UNIGINE
Source code (C#)
Debug.Log("Text: " + text);
Debug.LogFormat("Formatted text: {0}", text);
Source code (C#)
Log.Message("Debug info:" + text + "\n");
Log.Message("Debug info: {0}\n", new vec3(1, 2, 3));

See Also#

  • More types of messages in the Log class API.
  • The video tutorial demonstrating how to print user messages to console using C# Component System.

Drawing Debug Data#

Unity software:

Source code (C#)
Debug.DrawLine(Vector3.zero, new Vector3(5, 0, 0), Color.white, 2.5f);

Vector3 forward = transform.TransformDirection(Vector3.forward) * 10;
Debug.DrawRay(transform.position, forward, Color.green);

UNIGINE:

Source code (C#)
Visualizer.Enabled = 1;

/*..*/

Visualizer.RenderLine3D(vec3.ZERO, new vec3(5, 0, 0), vec4.ONE);
Visualizer.RenderVector(node.Position, node.GetDirection(MathLib.AXIS.Y) * 10, new vec4(1, 0, 0, 1));
Notice
The visualizer can be toggled on and off via show_visualizer 1 console command as well.

See Also#

  • More types of visualizations in the Visualizer class API.

Loading a Scene#

Unity software UNIGINE
Source code (C#)
SceneManager.LoadScene("YourSceneName",LoadSceneMode.Single);
Source code (C#)
World.LoadWorld("YourSceneName");

Accessing the GameObject / Node from Component#

Unity software UNIGINE
Source code (C#)
GameObject this_go = gameObject;
string n = gameObject.name;
Source code (C#)
Node this_node = node;
string n = node.Name;

See Also#

  • The video tutorial demonstrating how to access nodes from components using C# Component System.

Accessing a Component from the GameObject / Node#

Unity software:

Source code (C#)
MyComponent my_component = gameObject.GetComponent<MyComponent>();

UNIGINE:

Source code (C#)
MyComponent my_component = node.GetComponent<MyComponent>();
MyComponent my_component = GetComponent<MyComponent>(node);

Finding GameObjects / Nodes#

Unity software:

Source code (C#)
// Find a GameObject by name
GameObject myGameObj = GameObject.Find("My Game Object");

// Find the child named "ammo" of the gameobject "magazine" (magazine is a child of "gun").
Transform ammo_transform = gameObject.transform.Find("magazine/ammo");
GameObject ammo = ammo_transform.gameObject;

// Find GameObjects by the type of component assigned
MyComponent[] components = Object.FindObjectsOfType<MyComponent>();
foreach (MyComponent component in components)
{
        // ...
}

// Find GameObjects by tag
GameObject[] taggedGameObjects = GameObject.FindGameObjectsWithTag("MyTag");
foreach (GameObject gameObj in taggedGameObjects)
{
        // ...
}

UNIGINE:

Source code (C#)
// Find a Node by name
Node my_node = World.GetNodeByName("my_node");

// Find all nodes having this name
List<Node> nodes = new List<Node>();
World.GetNodesByName("my_node");

// Find the index of a direct child node
int index = node.FindChild("child_node");
Node direct_child = node.GetChild(index);

// Perform a recursive descend down the hierarchy to find a child Node by name
Node child = node.FindNode("child_node", 1);

// Find Nodes by the type of component assigned
MyComponent[] my_comps = FindComponentsInWorld<MyComponent>();
foreach(MyComponent comp in my_comps)
{
	Log.Message("{0}\n",comp.node.name);
}

Casting From Type to Type#

Downcasting (from a pointer-to-base to a pointer-to-derived) is performed similarly in both engines, by using the C# as native construction:

Unity software UNIGINE
Source code (C#)
Collider collider = gameObject.GetComponent<Collider>;
BoxCollider boxCollider = collider as BoxCollider;
Source code (C#)
Node node = World.GetNodeByName("my_mesh");
ObjectMeshStatic mesh = node as ObjectMeshStatic;

To perform Upcasting (from a pointer-to-derived to a pointer-to-base) you can simply use the instance itself:

Unity software UNIGINE
Source code (C#)
Collider collider = gameObject.GetComponent<Collider>;
BoxCollider boxCollider = collider as BoxCollider;
Collider coll = boxCollider;
Source code (C#)
Node node = World.GetNodeByName("my_mesh");
ObjectMeshStatic mesh = node as ObjectMeshStatic;
Unigine.Object obj = mesh;

Destroy GameObject / Node#

Unity software UNIGINE
Source code (C#)
Destroy(maGameObject);

// destroy the game object with 1 second delay
Destroy(maGameObject, 1);
Source code (C#)
node.DeleteLater();

node.DeleteForce(); // unsafe

To perform deferred removal of a node in UNIGINE, you can create a component that will be responsible for the timer and deletion.

Source code (C#)
// LifetimeController.cs

using Unigine;

public class LifetimeController : Component
{
	public float lifetime = 5.0f;

	void Update()
	{
		lifetime = lifetime - Game.IFps;
        if (lifetime < 0)
        {
            // destroy current node with its properties and components
			node.DeleteLater();
        }
	}
}

// MyComponent.cs
public class MyComponent : Component
{
	
	void Update()
	{
		if (/* a reason to die */)
		{
			LifetimeController lc = node.AddComponent<LifetimeController>();
			lc.lifetime = 2.0f;
		}
	}
}

Instantiating Prefab / Node Reference#

In Unity software, you instantiate a prefab using the Object.Instantiate function:

Source code (C#)
using UnityEngine;

public class MyComponent : MonoBehaviour
{
    public GameObject myPrefab;

    void Start()
    {
        Instantiate(myPrefab, new Vector3(0, 0, 0), Quaternion.identity);
    }
}

Then, you should specify the prefab to be instantiated in the script component parameters:

In UNIGINE, you should use World.LoadNode to load a hierarchy of nodes from a .node asset. In this case the hierarchy of nodes that was saved as a NodeReference will be added to the scene. You can refer to the asset either via a component parameter or manually by providing the virtual path to it:

Source code (C#)
using Unigine;

public class MyComponent : Component
{
	[ParameterFile(Filter = ".node")]
	public string node_to_spawn;
	
	void Update()
	{
		// load a hierarchy of nodes from the asset
		Node spawned = World.LoadNode(node_to_spawn);
		spawned.WorldPosition = node.WorldPosition;

		Node spawned_manually = World.LoadNode("nodes/node_reference.node");
	}
}

In case of using the approach of component parameters, you should also specify the .node asset:

You can also spawn the node reference as a single node (without extracting the content) in the world:

Source code (C#)
using Unigine;

public class MyComponent : Component
{
	void Update()
	{
		NodeReference nodeRef = new NodeReference("nodes/node_reference_0.node");
	}
}

Running Scripts in the Editor#

You are likely to be accustomed that Unity software enables you to extend the Editor using C# scripts. For this purpose you can use special attributes in your scripts:

  • [ExecuteInEditMode] — to execute the script logic during Edit mode, while your application is not running.
  • [ExecuteAlways] — to execute the script logic both as part of Play mode and when editing.

For example, this is how you write a component that makes the GameObject orient towards the certain point in the scene:

Source code (C#)
//C# Example (LookAtPoint.cs)
using UnityEngine;
[ExecuteInEditMode]
public class LookAtPoint : MonoBehaviour
{
    public Vector3 lookAtPoint = Vector3.zero;

    void Update()
    {
        transform.LookAt(lookAtPoint);
    }
}

UNIGINE doesn't support executing C# logic inside the Editor. Instead, you can write logic in UnigineScript to optimize a project creation process. UnigineScript is available for any programming workflow you have chosen for your project including C# .NET Core.

There are two methods to add a script to the project:

  • By creating a world script. Perform the following steps:
    1. Create a .usc script asset.

    2. Write logic. If necessary, add a condition checking if the Editor is loaded:

      Source code (UnigineScript)
      #include <core/unigine.h>
      vec3 lookAtPoint = vec3_zero;
      Node node;
      int init() {
      	node = engine.world.getNodeByName("material_ball");
      	return 1;
      }
      
      int update() {
      	if(engine.editor.isLoaded())
      		node.worldLookAt(lookAtPoint);
      	return 1;
      }
    3. Select the current world and specify the world script for it. Click Apply and reload the world.

    4. Check the Console window if there are any errors.

    After that the script logic will be executed in both Editor and application.

  • By using WorldExpression. For the same purpose you can use a built-in WorldExpression node executing scripts when added to the world:
    1. Click Create -> Logic -> Expression and place the new WorldExpression node in the world.
    2. Write logic in UnigineScript in the Source field:
      Source code (UnigineScript)
      {
      vec3 lookAtPoint = vec3_zero;
      Node node = engine.world.getNodeByName("my_node");
      node.worldLookAt(lookAtPoint);
      }
    3. Check the Console window if there are any errors.
    4. The logic will be executed immediately.

Triggers#

In addition to collision detection, Unity Collider components are accountable for being triggers that are executed when one collider enters the space of another.

Source code (C#)
public class MyComponent : MonoBehaviour
{
    void Start()
    {
        collider.isTrigger = true;
    }
    void OnTriggerEnter(Collider other)
    {
        // ...
    }
    void OnTriggerExit(Collider other)
    {
        // ...
    }
}

In UNIGINE, triggers are special built-in node types that raise events in certain situations:

The WorldTriger is the most common type that can be used in gameplay. Here is an example on how to use it:

Source code (C#)
using Unigine;
class MyComponent : Component
{
	WorldTrigger trigger;

	void enter_callback(Node incomer)
	{
		Log.Message("\n{0} has entered the trigger space\n", incomer.Name);
	}

	void Init()
	{
		trigger = node as WorldTrigger;
		if(trigger != null)
		{
			trigger.AddEnterCallback(enter_callback);
			trigger.AddLeaveCallback( leaver => Log.Message("{0} has left the trigger space", leaver.Name));
		}
	}
}

Input#

Unity Conventional Game Input:

Source code (C#)
public class MyPlayerController : MonoBehaviour
{
    void Update()
    {
        if (Input.GetButtonDown("Fire"))
        {
            // ...
        }
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");
        // ...
    }
}

UNIGINE:

Source code (C#)
class MyPlayerController : Component
{
    void Update()
    {
		if(Input.IsMouseButtonDown(Input.MOUSE_BUTTON.LEFT))
		{
			Log.Message("Left mouse button was clicked at {0}\n", Input.MouseCoord);
		}

		if (Input.IsKeyDown(Input.KEY.Q) && !Unigine.Console.Activity)
		{
			Log.Message("Q was pressed and the Console is not active.\n");
			App.Exit();
		}
    }
}

You can also use the ControlsApp class to handle control bindings. To configure the bindings, open the Controls settings:

Source code (C#)
class MyPlayerController : Component
{
    void Init()
	{
		// remapping states to keys and buttons
		ControlsApp.SetStateKey(Controls.STATE_FORWARD, 'w');
		ControlsApp.SetStateKey(Controls.STATE_BACKWARD, 's');
		ControlsApp.SetStateKey(Controls.STATE_MOVE_LEFT, 'a');
		ControlsApp.SetStateKey(Controls.STATE_MOVE_RIGHT, 'd');
		ControlsApp.SetStateButton(Controls.STATE_JUMP, App.BUTTON_LEFT);
	}
	void Update()
	{
		if (ControlsApp.ClearState(Controls.STATE_FORWARD) != 0)
		{
			Log.Message("FORWARD key pressed\n");
		}
		else if (ControlsApp.ClearState(Controls.STATE_BACKWARD) != 0)
		{
			Log.Message("BACKWARD key pressed\n");
		}
		else if (ControlsApp.ClearState(Controls.STATE_MOVE_LEFT) != 0)
		{
			Log.Message("MOVE_LEFT key pressed\n");
		}
		else if (ControlsApp.ClearState(Controls.STATE_MOVE_RIGHT) != 0)
		{
			Log.Message("MOVE_RIGHT key pressed\n");
		}
		else if (ControlsApp.ClearState(Controls.STATE_JUMP) != 0)
		{
			Log.Message("JUMP button pressed\n");
		}
	}
}

Raycasting#

In Unity software, Physics.Raycast is used. GameObjects should have a Collider component attached to take part in raycasting:

Source code (C#)
using UnityEngine;
public class ExampleClass : MonoBehaviour
{
	public Camera camera;

    void Update()
    {
    	// ignore the 2nd layer
        int layerMask = 1 << 2;
        layerMask = ~layerMask;

        RaycastHit hit;
        Ray ray = camera.ScreenPointToRay(Input.mousePosition);
        if (Physics.Raycast(ray, out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    }
}

In UNIGINE the same is handled by Intersections:

Source code (C#)
using Unigine;
class IntersectionExample : Component
{
	void Init()
	{
		Visualizer.Enabled = true;
	}
    void Update()
    {
    	ivec2 mouse = Input.MouseCoord;
		float length = 100.0f;
		vec3 start = Game.Player.WorldPosition;
		vec3 end = start + new vec3(Game.Player.GetDirectionFromScreen(mouse.x, mouse.y)) * length;

		// ignore surfaces that have certain bits of the Intersection mask enabled
		int mask = ~(1 << 2 | 1 << 4);

		WorldIntersectionNormal intersection = new WorldIntersectionNormal();

		Unigine.Object obj = World.GetIntersection(start, end, mask, intersection);

		if (obj)
		{
			vec3 point = intersection.Point;
			vec3 normal = intersection.Normal;
			Visualizer.RenderVector(point, point + normal, vec4.ONE);
			Log.Message("Hit {0} at {1}\n", obj.Name, point);
		}
	}
}
Last update: 19.05.2020
Build: ()