💻
Coding for Creatives Spring 2021
  • Hello
  • Class Exercises
    • Week 2 (Variable) Activities
      • Getting Blobby (Processing)
      • Unity Activity Notes
      • TouchDesigner Activity Notes
      • More Variable Activities
        • Star Wars Name Exercise
        • Mad Libs Exercise
    • Week 3 (If/Else Statements) Activities
      • Rubber Ducky Activity (Unity)
    • Week 4 (Loops) Activities
      • Using For and Foreach Loops in Unity
      • More Loop Activities
        • Movement Using If Statements In Processing
        • Moving Shapes in Processing
    • Week 5 (Arrays & Lists) Activities
      • Moving Squares Activity
    • Week 6 (Functions)
      • Mario Activity
      • Raycasting (Unity)
      • More Functions Activities
        • Snake (Processing)
    • Week 8 (Randomness & Object Interaction)
      • Bouncing Ball (Unity)
    • Week 9 (Creating Custom Objects)
      • Creating Custom Objects (Processing)
      • Cannon Game (Unity)
    • Week 10 (Sensors & TouchDesigner)
      • TouchOSC
      • More Activities
        • Audio-Reactive 3D Shapes
  • Glossary and Terms
    • Blank Space / Canvas Origin
    • Shapes / Primitives
    • Color
    • Movement
    • Control
    • Variables
      • Declaring Variables
      • Assigning a Variable
      • Using a Variable
      • Data Types
        • Floating Point or Float
        • Integer or Int
        • Boolean or Bool
        • String
      • Casting a Variable
    • Arrays
      • Creating Arrays
      • Assigning Values to Arrays
      • Using Array Elements
      • Multi-Dimensional Arrays
      • Common Errors
    • Conditional Statements (If/Else)
    • Operators
      • Relational Operators
      • Mathematical Operators
      • Logical Operators
    • Loops
      • While Loops
      • For Loops
      • Foreach Loops
    • Functions & Methods
      • Creating a Function
      • Calling or Invoking a Function
      • Parameters & Arguments
    • Interaction
      • Mouse Interaction
    • Objects, Classes & Libraries
      • Accessing Objects
    • Node-Based Programming
  • Processing Info
    • Overview
    • Interface
    • Template
    • Printing to the Console
  • Unity Info
    • Overview
    • The Default Interface
    • The Windows (Tabs)
      • Hierarchy Window
      • Scene Window
      • Project Window
      • Inspector Window
      • Game Window
      • Console Window
    • Other Layouts
      • Create a Custom Layout
  • TouchDesigner Info
    • Overview
    • Popular TOPs
    • Popular CHOPs
    • Popular SOPs
    • Popular DATs
  • Arduino Info
    • Arduinos!
    • The Parts
    • The Setup
      • Using the Serial Connection
      • Output Component Setup Examples
      • Input Component Setup Examples
      • Create a Night Light
  • Templates & Shortcuts
    • Power of Negative 1
    • Modifiers
    • Start Codes
      • Processing Start Code
      • HTML, CSS, JavaScript Start Code
    • WASD Movement Code
      • Processing Example
      • Unity Example (3D)
      • Unity Example (2D Platformer)
    • Parenting Example Script
  • Useful Links
    • Share & Show Off
    • Software & Apps
    • Free & Affordable Game Assets
Powered by GitBook
On this page
  • Parenting (Scene)
  • MoveObject.cs (Script)
  • ObjectDetails.cs (Script)
  • SwitchParent.cs (Script)
  • Test it!

Was this helpful?

  1. Templates & Shortcuts

Parenting Example Script

PreviousUnity Example (2D Platformer)NextShare & Show Off

Last updated 4 years ago

Was this helpful?

Download and inport this Unity Package to take a look at the scripts, scene, and see them work.

What's included:

  • Parenting (Scene)

  • MoveObject.cs (Script)

  • ObjectDetails.cs (Script)

  • SwitchParent.cs (Script)

Parenting (Scene)

This scene has a cube on the left and a sphere on the right and a capsule in the center. The capsule is the object that changes its parent when you press a button. It's default parent is an empty game object called Empty Object.

There is a UI Canvas with two buttons: Switch Parent and Reset Parent.

MoveObject.cs (Script)

This script is attached to both the cube and the sphere with the sphere having Move Opposite checked.

The script has the object it is attached to move when the Up Arrow or W key is pressed or when the Down Arrow or S key is pressed.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObject : MonoBehaviour
{
    public bool moveOpposite = false;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        // if the Up arrow or W key is pressed
        if (Input.GetKey(KeyCode.UpArrow) || Input.GetKey(KeyCode.W))
        {
            if (moveOpposite)
            {
                // Move down
                transform.Translate(Vector3.down * Time.deltaTime * 2);
            }
            else
            {
                // Move up
                transform.Translate(Vector3.up * Time.deltaTime * 2);
            }
        }

        // if the Down arrow or S key is pressed
        if (Input.GetKey(KeyCode.DownArrow) || Input.GetKey(KeyCode.S))
        {
            if (moveOpposite)
            {
                // Move up
                transform.Translate(Vector3.up * Time.deltaTime * 2);
            }
            else
            {
                // Move down
                transform.Translate(Vector3.down * Time.deltaTime * 2);
            }
        }

    }
}

ObjectDetails.cs (Script)

This script is attached to the object that is changing parents (the capsule) to keep track of its original parent.

It sets its Original Parent parameter upon playing the scene.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ObjectDetails : MonoBehaviour
{
    public Transform originalParent;

    // Start is called before the first frame update
    void Start()
    {
        // Immediate look for and set the original parent of the object this script is on
        originalParent = transform.parent;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

SwitchParent.cs (Script)

SwitchParent has functions for both buttons to run, so I attached it to the Canvas. I set the Affected Object to the Capsule, Parent Option 1 to the Cube, and Parent Option 2 to the Sphere within Unity.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SwitchParent : MonoBehaviour
{
    public Transform affectedObject;
    public Transform parentOption1;
    public Transform parentOption2;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void ChangeParent()
    {
        // if the parent is the first option
        if (affectedObject.parent == parentOption1)
        {
            // Switch to second option
            affectedObject.parent = parentOption2;
        }
        else
        // if the parent is the second option or none of the options
        {
            // Switch to first option
            affectedObject.parent = parentOption1;
        }
    }

    public void ResetParent()
    {
        // Get the ObjectDetails of the object and the original parent and set the parent to the original
        affectedObject.parent = affectedObject.GetComponent<ObjectDetails>().originalParent;
    }
}

Note: Start() and Update() aren't needed here, but I left them in, in case it makes it easier for you to understand where the two custom functions would appear.

ChangeParent() checks to see if the affected object is parented to the first option. If it is, it switches to the second option. If it isn't, it switches it to the first.

ResetParent() looks at the ObjectDetails script attached to the affected object to determine and set the parent to the original parent.

To call these functions, I have the button objects reference the SwitchParent script and call the specific function:

Test it!

When playing, the capsule should move with the parent object as well as appear as a child object in the Hierarchy window. When it's parented by its original parent, it will not move.

6KB
ParentingExample.zip
archive
ParentingExample.zip