Unity basic C # access between game objects

Source: Internet
Author: User

Script Language: C #

 

1. Create two objects in the Unity project: Cube and sphere.

2. Add the cubescript and spherescript for the cube and sphere respectively:

In spherescript, the two define a function dosomething (). The specific code of the script is as follows:

using UnityEngine;using System.Collections;public class SphereScript : MonoBehaviour {    public int radius = 5;    // Use this for initialization    void Start () {    }        // Update is called once per frame    void Update () {    }    public void DoSomething(){        Debug.Log("Hello ~");    }}

 

3. Access the sphere of an object in the cubescript script to change its color to red, and access the dosomething function in the spherescript. The specific code is as follows:

Using unityengine; using system. collections; public class cubescript: monobehaviour {// use this for initialization void start () {spherescript A = NULL; // obtain spherescript script a = gameobject. find ("sphere "). getcomponent <spherescript> (); debug. log ("spherescript's a =" +. radius); debug. log ("spherescript's function Domething:"); // call the function a of the spherescript. dosomething ();} // update is called once per frame void Update () {gameobject target = NULL; // access sphere to reference object target = gameobject. find ("sphere"); // Changes the color of the sphere to red target. renderer. material. color = color. red ;}}

 

4. Running effect:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.