2016-08-16 3 views
3

Я пытаюсь интегрировать карту Google в своем проекте Unity3D, используя это ниже C# код в моей карте игровой объект, который 3D обычный объект:C# сценарий интегрировать карты Google в заблуждение Unity3D

using UnityEngine; 
    using System.Collections; 

    public class GoogleMap : MonoBehaviour 
    { 
     public enum MapType 
     { 
      RoadMap, 
      Satellite, 
      Terrain, 
      Hybrid 
     } 
     public bool loadOnStart = true; 
     public bool autoLocateCenter = true; 
     public GoogleMapLocation centerLocation; 
     public int zoom = 13; 
     public MapType mapType; 
     public int size = 512; 
     public bool doubleResolution = false; 
     public GoogleMapMarker[] markers; 
     public GoogleMapPath[] paths; 

     void Start() { 
      if(loadOnStart) Refresh(); 
     } 

     public void Refresh() { 
      if(autoLocateCenter && (markers.Length == 0 && paths.Length == 0)) { 
       Debug.LogError("Auto Center will only work if paths or markers are used."); 
      } 
      StartCoroutine(_Refresh()); 
     } 

     IEnumerator _Refresh() 
     { 
      var url = "http://maps.googleapis.com/maps/api/staticmap"; 
      var qs = ""; 
      if (!autoLocateCenter) { 
       if (centerLocation.address != "") 
       qs += "center=" + WWW.UnEscapeURL (centerLocation.address); 
       else { 
        qs += "center=" + WWW.UnEscapeURL (string.Format ("{0},{1}", centerLocation.latitude, centerLocation.longitude)); 
       } 

       qs += "&zoom=" + zoom.ToString(); 
      } 
      qs += "&size=" + WWW.UnEscapeURL (string.Format ("{0}x{0}", size)); 
      qs += "&scale=" + (doubleResolution ? "2" : "1"); 
      qs += "&maptype=" + mapType.ToString().ToLower(); 
      var usingSensor = false; 
    #if UNITY_IPHONE 
      usingSensor = Input.location.isEnabledByUser && Input.location.status == LocationServiceStatus.Running; 
    #endif 
      qs += "&sensor=" + (usingSensor ? "true" : "false"); 

      foreach (var i in markers) { 
       qs += "&markers=" + string.Format ("size:{0}|color:{1}|label:{2}", i.size.ToString().ToLower(), i.color, i.label); 
       foreach (var loc in i.locations) { 
        if (loc.address != "") 
        qs += "|" + WWW.UnEscapeURL (loc.address); 
        else 
        qs += "|" + WWW.UnEscapeURL (string.Format ("{0},{1}", loc.latitude, loc.longitude)); 
       } 
      } 

      foreach (var i in paths) { 
       qs += "&path=" + string.Format ("weight:{0}|color:{1}", i.weight, i.color); 
       if(i.fill) qs += "|fillcolor:" + i.fillColor; 
       foreach (var loc in i.locations) { 
        if (loc.address != "") 
        qs += "|" + WWW.UnEscapeURL (loc.address); 
        else 
        qs += "|" + WWW.UnEscapeURL (string.Format ("{0},{1}", loc.latitude, loc.longitude)); 
       } 
      } 

      var req = new WWW (url + "?" + qs); 
      yield return req; 
      GetComponent().material.mainTexture = req.texture; 
     } 

    } 

    public enum GoogleMapColor 
    { 
     black, 
     brown, 
     green, 
     purple, 
     yellow, 
     blue, 
     gray, 
     orange, 
     red, 
     white 
    } 

    [System.Serializable] 
    public class GoogleMapLocation 
    { 
     public string address; 
     public float latitude; 
     public float longitude; 
    } 

    [System.Serializable] 
    public class GoogleMapMarker 
    { 
     public enum GoogleMapMarkerSize 
     { 
      Tiny, 
      Small, 
      Mid 
     } 
     public GoogleMapMarkerSize size; 
     public GoogleMapColor color; 
     public string label; 
     public GoogleMapLocation[] locations; 

    } 

    [System.Serializable] 
    public class GoogleMapPath 
    { 
     public int weight = 5; 
     public GoogleMapColor color; 
     public bool fill = false; 
     public GoogleMapColor fillColor; 
     public GoogleMapLocation[] locations; 
    } 

Я нашел ошибку на этой линии:

GetComponent().material.mainTexture = req.texture; 

Он показывает:

Using the generic method `UnityEngine.Component.GetComponent<T>()' requires `1'type argument(s) 

Как более подробно в следующем PICT УРЭС:

enter image description here

В Unity3D, есть некоторые ошибки, как указано в следующих рисунках:

enter image description here

Как вы можете видеть, в Inspector панели под картой сценария Google, он показывает:

The associated script cannot be loaded. Please fix any compile errors and assign a valid script. 

И дно вниз, она показывает:

Assets/GoogleMap.cs(79,17): error CS0411: The type arguments for method `UnityEngine.Component.GetComponent<T>()' cannot be inferred from the usage. Try specifying the type arguments explicitly 

С моим небольшим опытом работы с Unity3D, пожалуйста, помогите мне решить, как решить эту ошибку. Заранее спасибо.

+0

Принимая ответ правильный, пожалуйста, пойдите для ответа @Programmer «s. Я должен ему один :) –

+0

@UmairM lol Мы просто разделены на несколько секунд, поэтому мне все равно, с каким ответом он идет. Предполагая, что мы находимся на расстоянии 5 минут, тогда да. – Programmer

+0

Время не должно определять ответ сообщения. Качество – FrankerZ

ответ

3

Практически там.

Заменить

GetComponent().material.mainTexture = req.texture; 

с

GetComponent<Material>().mainTexture = req.texture; 

Если вы получаете во время выполнения null ошибку на этой строке кода, использование MeshRenderer поскольку изображение, которое вы закачанный показывает, что вы используете Mesh Renderer.

GetComponent<MeshRenderer>().material.mainTexture = req.texture; 
+1

Спасибо, и особенно за дополнительную статью о MeshRenderer. Это помогает мне еще больше. – SanitLee

2

Попробуйте изменить эту строку следующим образом:

GetComponent<Material>().mainTexture = req.texture; 

Это правильный синтаксис для использования GetComponent

+0

Спасибо в любом случае, мне просто нужно пойти на @ Programmer's, поскольку он появился мне всего на долю секунд раньше. – SanitLee

+2

Нет проблем. Пока вы получили помощь, это не имеет значения :) –

Смежные вопросы