2

Hia I've been trying to make an object "Tower" look at the object "Enemy" however I've been getting the error "An object reference is required for the non-static field, method, or property 'Enemy.position' "

This is the class for the Enemy where I've tried to define the position of the enemy for the Tower to reference to.

Does anyone know how this can be fixed? Thanks

public class Enemy : MonoBehaviour {

public float speed = 1.5f;
public Vector3 position;

private Vector3 target;

void Start()
{
    target = transform.position;
}

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        target.z = transform.position.z;
    }
    transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);

    position = GameObject.Find("enemy").transform.position;
}

}

Here is the class for the Tower where "var lookPos = Enemy.position - transform.position;" is causing the error.

public class Tower : MonoBehaviour {

public GameObject towerPrefab;
public float speed = 1f;

private bool canPlaceTower()
{
    return tower == null;
}


private GameObject tower;

// Use this for initialization
void Start()
{

}

void Update()
{
    var lookPos = Enemy.position - transform.position;
    lookPos.y = 0;
    var rotation = Quaternion.LookRotation(lookPos);
    transform.rotation = Quaternion.Lerp(transform.rotation, rotation, speed * Time.time);
    transform.Rotate(0, -90, 0);
}
}
Bradeurs
  • 53
  • 1
  • 8
  • Possible duplicate of [An object reference is required for the nonstatic field, method, or property on a Windows form](http://stackoverflow.com/questions/498400/an-object-reference-is-required-for-the-nonstatic-field-method-or-property-on) – TheLethalCoder Jan 20 '17 at 16:49
  • First step with any problem that you can't fix: Google (or your favourite search engine, I won't force you to use Google) it! – TheLethalCoder Jan 20 '17 at 16:50
  • Yeah I did try a few google searches but I couldn't seem to find my answer, I assumed I was using the wrong approach since I'm new to programming and thought that someone would point me in the right direction. – Bradeurs Jan 20 '17 at 16:52
  • You don't have to be a master in Google-fu to find an answer to this... https://www.google.co.uk/?gws_rd=ssl#q=An+object+reference+is+required+for+the+non-static+field%2C+method%2C+or+property+ – TheLethalCoder Jan 20 '17 at 16:53
  • 2
    The community is not very welcoming to newcomers these days ... – aybe Jan 20 '17 at 18:00
  • this is way easier if you use the `Transform.LookAt()` method. – yummypasta Jan 20 '17 at 18:23

1 Answers1

2

An object reference is required for the non-static field, method, or property 'Enemy.position'

This is because position in Enemy is not static.

Instead you could do something like this:

class Tower
{
    public Enemy Victim;

    /// ...
}

You would assign Victim in the Inspector then you would use that instead of your Enemy.position, however, this approach becomes limited because of the need to assign it manually.

Alternative solution:

A unique script in the tower that

  • searches for objects tagged Player
  • looks at the first one found, if any

Code:

using System.Linq;
using UnityEngine;

public class Tower : MonoBehaviour
{
    private void Update()
    {
        var objects = GameObject.FindGameObjectsWithTag("Player");
        if (!objects.Any())
            return;

        var target = objects.First();
        if (target == null)
            return;

        var p1 = transform.position;
        var p2 = target.transform.position;
        var position = new Vector3(p2.x, p1.y, p2.z); // does not bend to target
        transform.LookAt(position);
    }
}

This is very simple, instead you can do something better like if there are many players, pick closest one to tower:

private void Update()
{
    var objects = GameObject.FindGameObjectsWithTag("Player");
    if (!objects.Any())
        return;

    var distances = objects.Select(s => Vector3.Distance(transform.position, s.transform.position)).ToArray();
    var first = distances.First();
    var index = 0;
    var index1 = 0;
    foreach (var distance in distances)
    {
        if (distance < first)
        {
            index1 = index;
            break;
        }
        index++;
    }

    var target = objects[index1];
    if (target == null)
        return;

    var p1 = transform.position;
    var p2 = target.transform.position;
    var position = new Vector3(p2.x, p1.y, p2.z); // does not bend to target
    transform.LookAt(position);
}

Note that transition can be abrupt when the closest enemy changes, I'm leaving that to you :) (hint: Vector3.SmoothDamp)

aybe
  • 15,516
  • 9
  • 57
  • 105
  • Hia thank you for your answer, I appreciate the effort you put into this, but it causes the objects to disapear when an enemy tagged with that is placed, do you know what could be causing this? – Bradeurs Jan 20 '17 at 17:45
  • Without code I can't really help ... I think you should ask another question like 'Why does my object disappear ?' and post your current code (i.e. keep this question clean as it is). – aybe Jan 20 '17 at 18:06
  • I cant actually ask another question for another two days, but commenting out the "transform.LookAt(position);" seems to stop it disappearing at least – Bradeurs Jan 20 '17 at 18:34
  • Well, but that stops the effect you intended ... debug your program by setting breakpoints and using scene view and hierarchy ! You should be able to find what's the cause :) – aybe Jan 20 '17 at 19:13
  • A breakpoint on var p2 highlights the "first" value with a value of "10.1192942f" and then highlights p1 with the value of "(-5.0, 0.0, 0.0)", but I'm not entirely sure what that means – Bradeurs Jan 20 '17 at 19:19
  • 1
    The public Enemy is great. :) – simbabque Jan 20 '17 at 23:29