-1

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;
    } 
}
         
}
  • Your main goal is not clear for me. What is main object? what is object2? This code will be attached to which gameobject? What is "Refer the script himself"? –  Aug 22 '21 at 14:48
  • I improved edit I hope it is more understandable :D – OmerPasa3328 Aug 22 '21 at 17:23

2 Answers2

0

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.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • so simply I actually don't need to write anything ? – OmerPasa3328 Aug 22 '21 at 18:15
  • yes ^^ This basically equals writing `this.transform` or also `this.gameObject.transform` .. but usually in `c#` you can skip the `this` if there are no name conflicts with parameters – derHugo Aug 23 '21 at 05:49
0

Instead of object2.transform.position , use transform.position , It will work and it refers to the gameObject to which your script is attacked. Also for simplification , you can first declare Vector3 name = transform.position and then use that vector if you need to use it repeatedly.