1

I've created an empty object called Maps and created a child rawimage. This script is assigned to Maps and the child rawimage object has been assigned to the rawimage variable in the inspector.

When I play, the inspector shows no rawimage assigned and says "object reference not set to instance of object".

using System.Collections;
using UnityEngine;
using UnityEngine.UI;

public class GoogleAPI : MonoBehaviour {

    public string url;
    public RawImage img;
    public float lon = 3.7533f;
    public float lat = 53.3047f;
    public int zoom;
    public int mapHeight;
    public int mapWidth;
    public int scale;
    LocationInfo li;
    public enum mapType { roadMap, satelite, hybrid, terrain };
    public mapType mapSelected;

    private IEnumerator Map() {
        url = "https://maps.googleapis.com/maps/api/staticmap?center=" + lat + "," + lon +
            "&zoom=" + zoom + "&size=" + mapHeight + "x" + mapWidth + "&Scale=" + scale
            + "&maptype=" + mapSelected +
            "&markers=color:blue%7Clabel:S%7C40.702147,-74.015794&markers=color:green%7Clabel:G%7C40.711614," +
            "-74.012318&markers=color:red%7Clabel:C%7C40.718217,-73.998284&key=AIzaSyDh1_nS-l7nWOFWvt0Gg9-9dY_11qWzK_Q";
        WWW www = new WWW(url);
        yield return www;
        img.texture = www.texture;
        img.SetNativeSize();
    }

    private void Start() {
        img = gameObject.GetComponent<RawImage>();
        StartCoroutine(Map());
    }
}
  • Yes, it is zooming on the center of the map, google maps will center on the location you give it, so when you zoom in it will zoom on the lat and lon it is given, if you want it to zoom in to a specific point you will need to calculate that new location using you mouse's coordinates, and then update your lat and lon on that point. f you want to scroll around the map add buttons that adjust both the lat and lon of the map. – AresCaelum Mar 26 '18 at 12:42
  • You are right. I had the coordinates in wrong. Do I use Input.MousePosition to get mouse coordinates and update lat and lon? –  Mar 26 '18 at 20:17
  • This is an old question that is essentially the same as the new one I tried to ask but it got removed. So I've edited this one in hope it can be answered. Thats why the above comments don't make much sense. –  Apr 27 '18 at 17:42

1 Answers1

0

In the code you posted, you're never assigning anything to img. So, it is null, which leads to the "object reference not set to instance of object" error.

If you put a breakpoint on the line,

 img.texture = www.texture;

You'll probably see that img is null.

You need to create a RawImage somewhere and assign it to the img field.

3Dave
  • 28,657
  • 18
  • 88
  • 151
  • Thanks! I've done that, the error is gone but now I get a red question mark. Ive added a debug log message in the start function and its showing a new map is made. –  Apr 27 '18 at 18:23