Search code examples
c#unity-game-enginetransformgameobject

How to refer an object of himself with out saying his name in C#


I have several objects which I need to calculate distance form the main point(main) and increase distence betwen main and each object surrounding it, by taken chaos value. But I don't want to put a different script to each one. I want same script in each one.

To put it simply , this is what I am trying :
222 = 2 2 2

212= 2 1 2

222= 2 2 2

// 1 is main point

// 2 is other objects surrounding it

So how can I refer to object himself without saying his name ?

OR should I change the way I am intended to do?

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

public class DistanceMovement : MonoBehaviour
{

public int chaos = 0;
public GameObject main;        // I referred the main object
                               // which we calculete distance from
 float distance;                 

void Start()
{
    float distance = chaos;      // firts checking
}

void Update()
{
    // Gets the distance between 2 objects 
float distances = Vector3.Distance (main.transform.position, object2.transform.position);
    //how can I do that without saying objects name but saying it his himself??
    

    // checks whether there was increase in chaos lvls
     if (chaos - distance >= 0)
    {
        chaos - distance += distances;
    } 
}
         
}

Solution

  • I guess what you mean is simply

    float distances = Vector3.Distance (main.transform.position, transform.position);
    

    where transform is a property of MonoBehaviour (which your class inherits from) and returns

    The Transform attached to this GameObject.

    so the Transform of the GameObject this component is attached to.