unity 3d error CS0118 - unity3d

I get this error:
Assets/initadmod.cs(25,2): error CS0118: Admob' is anamespace' but a type' was expected
Please copy this script to your MonoDevelop to see where is error.
using UnityEngine;
using System.Collections;
using Admob;
namespace Admob {
namespace GoogleMobileAds {
public class initadmod : MonoBehaviour {
public static initadmod instance;
// Use this for initialization
void Start () {
instance = this;
Debug.Log("start unity demo-------------");
initAdmob();
}
public string baner_Adr;
public string fullbaner_Adr;
public string baner_IOS ;
public string fullbaner_IOS ;
Admob ad;
//bool isAdmobInited = false;
void initAdmob()
{
string adUnitIdbaner ;
string adUnitIdfull ;
// isAdmobInited = true;
#if UNITY_EDITOR
adUnitIdbaner = "baner_Adr";
adUnitIdfull = "fullbaner_Adr";
#elif UNITY_ANDROID
adUnitIdbaner = baner_Adr;
adUnitIdfull = fullbaner_Adr;
#elif UNITY_5 || UNITY_IOS || UNITY_IPHONE
adUnitIdbaner = baner_IOS;
adUnitIdfull = fullbaner_IOS;
#else
adUnitIdbaner = baner_Adr;
adUnitIdfull = fullbaner_Adr;
#endif
ad = Admob.Instance();
ad.bannerEventHandler += onBannerEvent;
ad.interstitialEventHandler += onInterstitialEvent;
ad.rewardedVideoEventHandler += onRewardedVideoEvent;
ad.nativeBannerEventHandler += onNativeBannerEvent;
ad.initAdmob(adUnitIdbaner, adUnitIdfull);
// ad.setTesting(true);
Debug.Log("admob inited -------------");
}
public bool ShowBanerOnPlay;
public bool _ShowFullOnBackToMainMenu;
public bool _ShowFullNowOnOpenGame;
public int ShowFullOndie;
/// <summary>
/// hiện baner nhỏ góc trên màn hình lúc chạy
/// </summary>
public void ShowBanerOnPlayGame()
{
if (ShowBanerOnPlay)
{
ShowBaner();
}
}
/// <summary>
/// hiện baner lúc chết
/// sau Showfullondie số lần chết mới cho hiện
/// </summary>
public void ShowFullOnDie()
{
if (UImanager.uimanager.showbane >= ShowFullOndie-1)
{
showInterstitial();
UImanager.uimanager.showbane = 0;
}
}
/// <summary>
/// hiện qc khi đến menu chính
/// </summary>
public void ShowFullOnBackToMainMenu()
{
if (_ShowFullOnBackToMainMenu)
{
showInterstitial();
}
}
/// <summary>
/// hiện quảng cáo khi mới mở game ra khi hết mục dowload
/// </summary>
public void ShowFullNowOnOpenGame()
{
if (_ShowFullNowOnOpenGame)
{
showInterstitial();
}
}
void showInterstitial()
{
if (ad.isInterstitialReady())
{
ad.showInterstitial();
}
else
{
ad.loadInterstitial();
}
}
void ShowBaner()
{
Admob.Instance().showBannerRelative(AdSize.SmartBanner, AdPosition.TOP_CENTER, 0);
}
public void HideBaner()
{
Admob.Instance().removeBanner();
}
void onInterstitialEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onAdLoaded)
{
Admob.Instance().showInterstitial();
}
}
void onBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobBannerEvent---" + eventName + " " + msg);
}
void onRewardedVideoEvent(string eventName, string msg)
{
Debug.Log("handler onRewardedVideoEvent---" + eventName + " " + msg);
}
void onNativeBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobNativeBannerEvent---" + eventName + " " + msg);
}
}
}
}

On line 25 you are declaring
Admob ad;
but Admob is a namespace, not a class, so you need to add the class to your declaration, maybe something like (this is just an example)
Admob.GoogleMobileAds.initadmod ad;

Related

How to display text in Unity game

I inherited by my ex collegue a Unity game. Now I need to implement this behaviour. The game consist in a car drive by user using Logitech steering.
Now I need to show a Text every X minute in a part of the screen like "What level of anxiety do you have ? " Ad the user should to set a value from 0 to 9 using the Logitech steering but I really don't know where to start.
This is my manager class:
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
namespace DrivingTest
{
// Braking test Manager
public class BtManager : BaseTestManger
{
// Public variables
public BreakCar breakCar;
public float minBrakeThreshold = 0.2f;
internal int vehicalSpeed;
internal int noOfEvents;
internal float durationOfTest;
// Private variables
private IRDSPlayerControls playerControlCar;
protected int xSpeed;
protected int ySpeed;
private float brakeEventStartTime;
private float brakeEventDifferenceTime;
private SafetyDistanceCheck safetyDistanceCheck;
protected float totalSafetyDistance;
protected int totalSafetyDistanceCount;
private List<float> averageEventReactionTime = new List<float>();
#region Init
// Use this for initialization
public override void Start()
{
base.Start();
playerControlCar = car.GetComponent<IRDSPlayerControls>();
safetyDistanceCheck = car.GetComponent<SafetyDistanceCheck>();
}
public override void OnEnable()
{
base.OnEnable();
BreakCar.BrakeStart += BrakeCarEvent;
BreakCar.BrakeEventEnd += CallTestOver;
}
public override void OnDisable()
{
base.OnDisable();
BreakCar.BrakeStart -= BrakeCarEvent;
BreakCar.BrakeEventEnd -= CallTestOver;
}
protected override void SetUpCar()
{
car.AddComponent<SelfDriving>();
}
#endregion
/// <summary>
/// Calls the main Test over method.
/// </summary>
private void CallTestOver()
{
GameManager.Instance.Testover();
}
protected override void OnSceneLoaded(eTESTS test)
{
UiManager.Instance.UpdateInstructions(Constants.BT_INSTRUCTION);
}
protected override void GetApiParams()
{
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.X_SPEED:
xSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.Y_SPEED:
ySpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.SPEED_OF_VEHICLE:
vehicalSpeed = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.NUMBER_OF_EVENTS:
noOfEvents = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.DURATION_OF_TEST:
durationOfTest = float.Parse(item.Value) * 60; //converting minutes into seconds
break;
}
}
SetupBrakeCar();
}
}
protected virtual void SetupBrakeCar()
{
DOTween.Clear();
durationOfTest = noOfEvents * Random.Range(10,20); // The random value is the time between two consecutive tests.
breakCar.SetInitalParams(new BrakeCarInit
{
carMaxSpeed = vehicalSpeed * 0.95f,
durationOfTest = durationOfTest,
noOfEvents = noOfEvents,
xSpeed = xSpeed,
ySpeed = ySpeed
});
breakCar.distanceCheck = true;
}
protected override void SubmitRestultToServer()
{
SubmitTest submitTest = new SubmitTest
{
outputParameters = new List<SaveOutputParameter>
{
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_REACTION_TIME,
value = ((int)(GetEventReactionTimeAvg () * Constants.FLOAT_TO_INT_MULTIPLAYER)).ToString()
},
new SaveOutputParameter
{
id = (int)ePARAMETERS.OUT_AVG_RT,
value = GetReactionResult().ToString()
}
}
};
WebService.Instance.SendRequest(Constants.API_URL_FIRST_SAVE_TEST_RESULT, JsonUtility.ToJson(submitTest), SubmitedResultCallback);
}
protected override void ShowResult()
{
UiManager.Instance.UpdateStats(
(
"1. " + Constants.EVENT_REACTION + (GetEventReactionTimeAvg() * Constants.FLOAT_TO_INT_MULTIPLAYER).ToString("0.00") + "\n" +
"2. " + Constants.REACTION_TIME + reactionTest.GetReactionTimeAvg().ToString("0.00")
));
}
public void LateUpdate()
{
//Debug.Log("TH " + .Car.ThrottleInput1 + " TH " + playerControlCar.Car.ThrottleInput + " brake " + playerControlCar.Car.Brake + " brake IP " + playerControlCar.Car.BrakeInput);
//Debug.Log("BrakeCarEvent "+ brakeEventStartTime + " Player car " + playerControlCar.ThrottleInput1 + " minBrakeThreshold " + minBrakeThreshold);
if (brakeEventStartTime > 0 && playerControlCar.Car.ThrottleInput1 > minBrakeThreshold)
{
brakeEventDifferenceTime = Time.time - brakeEventStartTime;
Debug.Log("Brake event diff " + brakeEventDifferenceTime);
Debug.Log("Throttle " + playerControlCar.Car.ThrottleInput1);
averageEventReactionTime.Add(brakeEventDifferenceTime);
brakeEventStartTime = 0;
safetyDistanceCheck.GetSafetyDistance(SafetyDistance);
}
}
private void SafetyDistance(float obj)
{
totalSafetyDistance += obj;
++totalSafetyDistanceCount;
}
/// <summary>
/// Records the time when the car ahead starts braking
/// </summary>
protected void BrakeCarEvent()
{
brakeEventStartTime = Time.time;
Debug.Log("BrakeCarEvent ");
}
/// <summary>
/// calculates the average time taken to react
/// </summary>
public float GetEventReactionTimeAvg()
{
float avg = 0;
foreach (var item in averageEventReactionTime)
{
avg += item;
}//noofevents
return avg / (float)averageEventReactionTime.Count;
}
}
}
EDIT
I create new class FearTest:
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace DrivingTest
{
public class FearTest : MonoBehaviour
{
//public GameObject redDot;
public TextMeshPro textAnsia2;
public TextMesh textAnsia3;
public int shouldEvaluateTest = 0; // 0 - false, 1 - true
public int secondsInterval;
public int secondsToDisaply;
public int radiusR1;
public int radiusR2;
public int reactionTestDuration;
public int maxDots;
public float dotRadius = 1;
private float endTime;
private float dotDisaplyAtTime;
private List<float> dotDisplayReactTime = new List<float>();
private int missedSignals;
private int currentDotsCount;
private bool isReactionAlreadyGiven;
public bool ShouldEvaluateTest
{
get
{
return shouldEvaluateTest != 0;
}
}
void OnEnable()
{
GameManager.TestSceneLoaded += OnSceneLoaded;
}
private void OnDisable()
{
GameManager.TestSceneLoaded -= OnSceneLoaded;
}
#region Scene Loaded
private void OnSceneLoaded(eTESTS test)
{
if (SceneManager.GetActiveScene().name != test.ToString())
return;
Reset();
GetApiParams();
}
#endregion
private void GetApiParams()
{
#if UNITY_EDITOR
if (!GameManager.Instance)
{
Init();
return;
}
#endif
Debug.Log("called rt");
NextTestOutput nextTestOutput = GameManager.Instance.currentTest;
if (nextTestOutput.content != null && nextTestOutput.content.Count > 0)
{
foreach (var item in nextTestOutput.content[0].listInputParameter)
{
switch ((ePARAMETERS)item.id)
{
case ePARAMETERS.RT_ENABLE:
shouldEvaluateTest = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RT_DURATION:
reactionTestDuration = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_FREQ:
secondsInterval = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_MAX_COUNT:
maxDots = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R1:
radiusR1 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_RADIUS_R2:
radiusR2 = System.Convert.ToInt32(item.Value);
break;
case ePARAMETERS.RED_DOT_SIZE:
dotRadius = float.Parse(item.Value)/10f;
break;
case ePARAMETERS.RED_DOT_TIME:
secondsToDisaply = System.Convert.ToInt32(item.Value);
break;
}
}
Debug.Log("called rt "+ shouldEvaluateTest);
/*if (ShouldEvaluateTest)
{
Init();
}*/
Init();//dopo bisogna sistemare il shoudl evaluatetest
}
}
Coroutine displayCoroutine;
public void Init()
{
endTime = Time.time + reactionTestDuration + 10;
SetRedDotSize();
displayCoroutine = StartCoroutine(RedDotDisplay());
}
private IEnumerator RedDotDisplay()
{
yield return new WaitForSeconds(2);
while (true)
{
SetRandomDotPosition();
RedDot(true);
isReactionAlreadyGiven = false;
dotDisaplyAtTime = Time.time;
currentDotsCount++;
yield return new WaitForSeconds(secondsToDisaply);
if(!isReactionAlreadyGiven)
{
missedSignals++;
}
RedDot(false);
if ((reactionTestDuration > 0 && endTime <= Time.time) || (maxDots > 0 && currentDotsCount >= maxDots))
break;
float waitTime = secondsInterval - secondsToDisaply;
yield return new WaitForSeconds(waitTime);
}
}
private void Update()
{
if (!ShouldEvaluateTest)
return;
if (!isReactionAlreadyGiven && /*redDot.activeSelf &&*/ (LogitechGSDK.LogiIsConnected(0) && LogitechGSDK.LogiButtonIsPressed(0, 23)))
{
isReactionAlreadyGiven = true;
float reactionTime = Time.time - dotDisaplyAtTime;
Debug.Log("Reaction Time RT : " + reactionTime);
RedDot(false);
dotDisplayReactTime.Add(reactionTime);
}
}
public double GetReactionTimeAvg()
{
double avg = 0;
foreach (var item in dotDisplayReactTime)
{
avg += item;
}
//avg / currentDotsCount
return avg / (float)dotDisplayReactTime.Count;
}
public double GetMissedSignals()
{
return ((float) missedSignals / (float) currentDotsCount) * 100;
}
private void RedDot(bool state)
{
//redDot.SetActive(state);
textAnsia2.SetText("Pippo 2");
}
private void SetRedDotSize()
{
//redDot.transform.localScale *= dotRadius;
textAnsia2.transform.localScale *= dotRadius;
textAnsia3.transform.localScale *= dotRadius;
}
private void SetRandomDotPosition()
{
//redDot.GetComponent<RectTransform>().anchoredPosition = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2)*scale;
float scale = ((Screen.height*0.9f) / radiusR2) * 0.9f;
Vector3 pos = GetRandomPointBetweenTwoCircles(radiusR1, radiusR2) * scale;
Debug.Log("RT temp pos : " + pos);
pos = new Vector3(500, 500, 0);
Debug.Log("RT pos : " + pos);
// redDot.transform.position = pos;
Vector3 pos2 = new Vector3(20, 20, 0);
Debug.Log("text ansia 2 : " + pos2);
textAnsia2.transform.position = pos2;
textAnsia3.transform.position = pos;
}
#region Getting Red Dot b/w 2 cricles
/*
Code from : https://gist.github.com/Ashwinning/89fa09b3aa3de4fd72c946a874b77658
*/
/// <summary>
/// Returns a random point in the space between two concentric circles.
/// </summary>
/// <param name="minRadius"></param>
/// <param name="maxRadius"></param>
/// <returns></returns>
Vector3 GetRandomPointBetweenTwoCircles(float minRadius, float maxRadius)
{
//Get a point on a unit circle (radius = 1) by normalizing a random point inside unit circle.
Vector3 randomUnitPoint = Random.insideUnitCircle.normalized;
//Now get a random point between the corresponding points on both the circles
return GetRandomVector3Between(randomUnitPoint * minRadius, randomUnitPoint * maxRadius);
}
/// <summary>
/// Returns a random vector3 between min and max. (Inclusive)
/// </summary>
/// <returns>The <see cref="UnityEngine.Vector3"/>.</returns>
/// <param name="min">Minimum.</param>
/// <param name="max">Max.</param>
Vector3 GetRandomVector3Between(Vector3 min, Vector3 max)
{
return min + Random.Range(0, 1) * (max - min);
}
#endregion
#region Reset
private void Reset()
{
if (displayCoroutine != null)
StopCoroutine(displayCoroutine);
RedDot(false);
shouldEvaluateTest = 0;
reactionTestDuration = 0;
secondsInterval = 0;
missedSignals = 0;
maxDots = 0;
radiusR1 = 0;
radiusR2 = 0;
dotRadius = 1;
secondsToDisaply = 0;
endTime = 0;
dotDisaplyAtTime = 0;
dotDisplayReactTime.Clear();
//redDot.transform.localScale = Vector3.one;
textAnsia2.transform.localScale = Vector3.one;
textAnsia3.transform.localScale = Vector3.one;
currentDotsCount = 0;
isReactionAlreadyGiven = true;
}
#endregion
}
}
When "SetRandomDotPosition" method is called, in my scene I can display in a random position of the screen the RedDot (that is a simple image with a red dot), but I m not able to display my textAnsia2. How can I fixed it ?
I hope this will help you to get started :
https://vimeo.com/709527359
the scripts:
https://imgur.com/a/csNKwEh
I hope that in the video i covered every step that i've made.
Edit: The only thing is for you to do is to make the input of the Wheel to work on the slider. Try to make a simple script: when the text is enabled then the input from a joystick to work on that . When is disabled switch it back for his purpose .

Admob for Unity app does not show add

I have a problem with admob for unity app, I used documentation to add admob, I used video tutorial from youtube and I tried demo app (hello world from admob), but the result is the same, ad banners does not appear in my apps, as for, if use interstitials, when I try to show it, my app crashes. However, in console there is a dummy message.
my code
using GoogleMobileAds.Api;
public class AdMobManager : MonoBehaviour {
private BannerView bannerView;
[SerializeField] private string appID = "";
[SerializeField] private string bannerID = "";
[SerializeField] private string regularAD = "";
private void Awake(){
MobileAds.Initialize(appID);
}
public void OnClickShowBanner() {
this.RequestBanner();
}
public void OnClickShowAd() {
this.RequestReqularAd();
}
private void RequestReqularAd() {
InterstitialAd AD = new InterstitialAd(regularAD);
AdRequest request = new AdRequest.Builder().Build();
AD.LoadAd(request);
}
public void RequestBanner() {
bannerView = new BannerView(bannerID, AdSize.Banner, AdPosition.Bottom);
AdRequest request = new AdRequest.Builder().Build();
bannerView.LoadAd(request);
}
}
You can use this simple code for admob banner. some time it takes time to display banner ad but this script worked fine.
Source
public class GoogleMobileAdsDemoScript : MonoBehaviour
{
private BannerView bannerView;
public void Start()
{
this.RequestBanner();
}
private void RequestBanner()
{
#if UNITY_ANDROID
string adUnitId = "ca-app-pub-3940256099942544/6300978111";
#elif UNITY_IPHONE
string adUnitId = "ca-app-pub-3940256099942544/2934735716";
#else
string adUnitId = "unexpected_platform";
#endif
// Create a 320x50 banner at the top of the screen.
bannerView = new BannerView(adUnitId, AdSize.Banner, AdPosition.Top);
// Create an empty ad request.
AdRequest request = new AdRequest.Builder().Build();
// Load the banner with the request.
bannerView.LoadAd(request);
}
}
Source code available https://github.com/unity-plugins/Unity-Admob/blob/master/AdmobPluginRes/admobdemo.cs
using UnityEngine;
using admob;
public class admobdemo : MonoBehaviour {
Admob ad;
string appID="";
string bannerID="";
string interstitialID="";
string videoID="";
string nativeBannerID = "";
void Start () {
Debug.Log("start unity demo-------------");
initAdmob();
}
void Update () {
if (Input.GetKeyUp (KeyCode.Escape)) {
Debug.Log(KeyCode.Escape+"-----------------");
}
}
void initAdmob()
{
#if UNITY_IOS
appID="ca-app-pub-3940256099942544~1458002511";
bannerID="ca-app-pub-3940256099942544/2934735716";
interstitialID="ca-app-pub-3940256099942544/4411468910";
videoID="ca-app-pub-3940256099942544/1712485313";
nativeBannerID = "ca-app-pub-3940256099942544/3986624511";
#elif UNITY_ANDROID
appID="ca-app-pub-3940256099942544~3347511713";
bannerID="ca-app-pub-3940256099942544/6300978111";
interstitialID="ca-app-pub-3940256099942544/1033173712";
videoID="ca-app-pub-3940256099942544/5224354917";
nativeBannerID = "ca-app-pub-3940256099942544/2247696110";
#endif
AdProperties adProperties = new AdProperties();
adProperties.isTesting = true;
ad = Admob.Instance();
ad.bannerEventHandler += onBannerEvent;
ad.interstitialEventHandler += onInterstitialEvent;
ad.rewardedVideoEventHandler += onRewardedVideoEvent;
ad.nativeBannerEventHandler += onNativeBannerEvent;
ad.initSDK(appID,adProperties);//reqired,adProperties can been null
}
void OnGUI(){
if (GUI.Button(new Rect(120, 0, 100, 60), "showInterstitial"))
{
Debug.Log("touch inst button -------------");
if (ad.isInterstitialReady())
{
ad.showInterstitial();
}
else
{
ad.loadInterstitial(interstitialID);
}
}
if (GUI.Button(new Rect(240, 0, 100, 60), "showRewardVideo"))
{
Debug.Log("touch video button -------------");
if (ad.isRewardedVideoReady())
{
ad.showRewardedVideo();
}
else
{
ad.loadRewardedVideo(videoID);
}
}
if (GUI.Button(new Rect(0, 100, 100, 60), "showbanner"))
{
Admob.Instance().showBannerRelative(bannerID,AdSize.SMART_BANNER, AdPosition.BOTTOM_CENTER);
}
if (GUI.Button(new Rect(120, 100, 100, 60), "showbannerABS"))
{
Admob.Instance().showBannerAbsolute(bannerID,AdSize.BANNER, 20, 220,"mybanner");
}
if (GUI.Button(new Rect(240, 100, 100, 60), "removebanner"))
{
Admob.Instance().removeBanner();
Admob.Instance().removeBanner("mybanner");
}
if (GUI.Button(new Rect(0, 200, 100, 60), "showNative"))
{
Admob.Instance().showNativeBannerRelative(nativeBannerID,new AdSize(320,280), AdPosition.BOTTOM_CENTER);
}
if (GUI.Button(new Rect(120, 200, 100, 60), "showNativeABS"))
{
Admob.Instance().showNativeBannerAbsolute(nativeBannerID,new AdSize(-1,132), 0, 300);
}
if (GUI.Button(new Rect(240, 200, 100, 60), "removeNative"))
{
Admob.Instance().removeNativeBanner();
}
}
void onInterstitialEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobEvent---" + eventName + " " + msg);
if (eventName == AdmobEvent.onAdLoaded)
{
Admob.Instance().showInterstitial();
}
}
void onBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobBannerEvent---" + eventName + " " + msg);
}
void onRewardedVideoEvent(string eventName, string msg)
{
Debug.Log("handler onRewardedVideoEvent---" + eventName + " rewarded: " + msg);
}
void onNativeBannerEvent(string eventName, string msg)
{
Debug.Log("handler onAdmobNativeBannerEvent---" + eventName + " " + msg);
}
}

error cs0103 the name does not exist in the current context

I have my game with facebook invite integrated using unity3d. When switched to Android, everything works fine but when I switch to WebGL, I get the following error:
error CS0103: The name `LoggedSuccefull' does not exist in the current context
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using UnityEngine.SceneManagement;
#if FACEBOOK
using Facebook.Unity;
#endif
public class FacebookManager : MonoBehaviour {
private bool LoginEnable;
public GameObject facebookButton;
//1.3.3
private string lastResponse = string.Empty;
public static string userID;
public static List<FriendData> Friends = new List<FriendData> ();
public bool logged;
protected string LastResponse {
get {
return this.lastResponse;
}
set {
this.lastResponse = value;
}
}
private string status = "Ready";
protected string Status {
get {
return this.status;
}
set {
this.status = value;
}
}
bool loginForSharing;
public static FacebookManager THIS;
void Awake () {
if (THIS == null)
THIS = this;
else if (THIS != this)
Destroy (gameObject);
DontDestroyOnLoad (this);
}
void OnEnable () {
#if PLAYG
NetworkManager.OnLoginEvent += GetUserName;
#endif
}
void OnLevelWasLoaded () {
if (logged && SceneManager.GetActiveScene ().name == "game")
LoggedSuccefull ();
}
void OnDisable () {
#if PLAYG
NetworkManager.OnLoginEvent -= GetUserName;
#endif
}
#if PLAYG || GAMESPARKS
public FriendData GetCurrentUserAsFriend () {
//code
}
#endif
#region FaceBook_stuff
#if FACEBOOK
public void CallFBInit () {
Debug.Log ("init facebook");
FB.Init (OnInitComplete, OnHideUnity);
}
private void OnInitComplete () {
Debug.Log ("FB.Init completed: Is user logged in? " + FB.IsLoggedIn);
if (FB.IsLoggedIn) {//1.3
CallFBLogin ();
}
}
private void OnHideUnity (bool isGameShown) {
Debug.Log ("Is game showing? " + isGameShown);
}
void OnGUI () {
if (LoginEnable) {
CallFBLogin ();
LoginEnable = false;
}
}
public void CallFBLogin () {
Debug.Log ("login");
FB.LogInWithReadPermissions (new List<string> () { "public_profile", "email", "user_friends" }, this.HandleResult);
}
public void CallFBLoginForPublish () {
FB.LogInWithPublishPermissions (new List<string> () { "publish_actions" }, this.HandleResult);
}
public void CallInvite () {
this.Status = "Logged FB.AppEvent";
FB.Mobile.AppInvite (new Uri ("//URI Here"), callback: this.HandleResultInvite);
// NOTE !! create your app link here https://developers.facebook.com/quickstarts/?platform=app-links-host
}
protected void HandleResultInvite (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
public void CallFBLogout () {
FB.LogOut ();
//code
}
public void Share () {
if (!FB.IsLoggedIn) {
//code
}
protected void HandleResult (IResult result) {
if (result == null) {
this.LastResponse = "Null Response\n";
Debug.Log (this.LastResponse);
return;
}
// this.LastResponseTexture = null;
// Some platforms return the empty string instead of null.
if (!string.IsNullOrEmpty (result.Error)) {
this.Status = "Error - Check log for details";
this.LastResponse = "Error Response:\n" + result.Error;
Debug.Log (result.Error);
} else if (result.Cancelled) {
this.Status = "Cancelled - Check log for details";
this.LastResponse = "Cancelled Response:\n" + result.RawResult;
Debug.Log (result.RawResult);
} else if (!string.IsNullOrEmpty (result.RawResult)) {
this.Status = "Success - Check log for details";
this.LastResponse = "Success Response:\n" + result.RawResult;
LoggedSuccefull ();//1.3
} else {
this.LastResponse = "Empty Response\n";
Debug.Log (this.LastResponse);
}
}
void LoggedSuccefull () {//1.3
logged = true;
facebookButton.SetActive (false);//1.3.3
if (PlayerPrefs.GetInt ("Facebook_Logged") == 0) {
GameObject rewardPopup = Instantiate (Resources.Load ("Reward")) as GameObject;
rewardPopup.transform.GetChild (0).GetComponent<RewardIcon> ().SetIconSprite (0);
InitScript.Instance.AddGems (10);
}
PlayerPrefs.SetInt ("Facebook_Logged", 1);
PlayerPrefs.Save ();
if (SceneManager.GetActiveScene ().name != "game")
return;
//Debug.Log(result.RawResult);
userID = AccessToken.CurrentAccessToken.UserId;
GetPicture (AccessToken.CurrentAccessToken.UserId);
}
void GetUserName () {
FB.API ("/me?fields=first_name", HttpMethod.GET, GettingNameCallback);
}
private void GettingNameCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error)) {
IDictionary dict = result.ResultDictionary as IDictionary;
string fbname = dict ["first_name"].ToString ();
#endif
}
}
void GetPicture (string id) {
FB.API ("/" + id + "/picture", HttpMethod.GET, this.ProfilePhotoCallback);
}
private void ProfilePhotoCallback (IGraphResult result) {
if (string.IsNullOrEmpty (result.Error) && result.Texture != null) {
Sprite sprite = new Sprite ();
sprite = Sprite.Create (result.Texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
InitScript.profilePic = sprite;
#endif
}
}
public void SaveScores () {
//code
}
public void ReadScores () {
FB.API ("/me/objects/object", HttpMethod.GET, APICallBack);
}
public void GetFriendsPicture () {
FB.API ("me/friends?fields=picture", HttpMethod.GET, RequestFriendsCallback);
}
private void RequestFriendsCallback (IGraphResult result) {
if (!string.IsNullOrEmpty (result.RawResult)) {
// Debug.Log (result.RawResult);
//code
}
//}
}
//print(firstGroup["id"] + " " + firstGroup["title"]);
}
//this.gamerGroupCurrentGroup = (string)firstGroup["id"];
}
}
if (!string.IsNullOrEmpty (result.Error)) {
Debug.Log (result.Error);
}
}
}
public void GetPictureByURL (string url, FriendData friend) {
StartCoroutine (GetPictureCor (url, friend));
}
IEnumerator GetPictureCor (string url, FriendData friend) {
Sprite sprite = new Sprite ();
WWW www = new WWW (url);
yield return www;
sprite = Sprite.Create (www.texture, new Rect (0, 0, 50, 50), new Vector2 (0, 0), 1f);
friend.picture = sprite;
// print ("get picture for " + url);
}
public void APICallBack (IGraphResult result) {
Debug.Log (result);
}
#endif
#endregion
}
public class FriendData {
public string userID;
public string FacebookID;
public Sprite picture;
public int level;
public GameObject avatar;
}
Any help would be highly appreciated

Facebook login page doesn't show my score only happens for admin

after I log onto Facebook and everything, it works fine but when I try to show my friend's score it doesn't brings up the score the score would be zero all the time, except for the admin account which is mine, it shows up my actual score, and here are the scripts for the Facebook and also for the score manager of mine, any suggestions?
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class ScoreManager : MonoBehaviour {
public static int score;
Text scoretext;
void Start ()
{
scoretext = GetComponent<Text> () ;
//score = 0;
score = PlayerPrefs.GetInt("CurrentPlayerScore");
}
void Update ()
{
if (score <0)
score = 0;
scoretext.text = "" + score;
}
public static void AddPoints (int pointsToAdd)
{
score +=pointsToAdd;
PlayerPrefs.SetInt ("CurrentPlayerScore", score);
}
public static void Rest()
{
score = 0;
PlayerPrefs.SetInt("CurrentPlayerScore", score);
}
}
and this is Facebook's one
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
public class FBholder : MonoBehaviour
{
public GameObject UIFBIsLoggedIn;
public GameObject UIFBIsNotLoggedIn;
public GameObject UIFBAvatar;
public GameObject UIFUserName;
private List<object> scoresList = null;
public GameObject ScoreEntryPanel;
public GameObject ScoreScrollList;
public static int score;
private Dictionary<string, string> profile = null;
void Awake()
{
FB.Init (SetInit, OnHideUnity);
}
void Start()
{
score = PlayerPrefs.GetInt("CurrentPlayerScore");
}
private void SetInit()
{
Debug.Log ("FB Init done.");
if(FB.IsLoggedIn)
{
DealWithFBMenus(true);
Debug.Log ("FB Logged In");
}
else
{
DealWithFBMenus(false);
}
}
private void OnHideUnity(bool isGameShown)
{
if(!isGameShown)
{
Time.timeScale =0;
}
else
{
Time.timeScale =1;
}
}
public void FBlogin()
{
FB.Login ("email,publish_actions", AuthCallback);
}
void AuthCallback (FBResult result)
{
if (FB.IsLoggedIn)
{
Debug.Log ("FB Login worked!");
DealWithFBMenus(true);
}
else
{
Debug.Log ("Fb Login fail");
DealWithFBMenus(false);
}
}
void DealWithFBMenus (bool isLoggedIn)
{
if(isLoggedIn)
{
UIFBIsLoggedIn.SetActive(true);
UIFBIsNotLoggedIn.SetActive(false);
FB.API (Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
FB.API ("/me?field=id,first_name",Facebook.HttpMethod.GET, DealWiththeUserName);
}
else
{
UIFBIsLoggedIn.SetActive(false);
UIFBIsNotLoggedIn.SetActive(true);
}
}
void DealWithProfilePicture(FBResult result)
{
if (result.Error != null)
{
Debug.Log ("Problem with getting profile picture");
FB.API (Util.GetPictureURL("me", 128, 128), Facebook.HttpMethod.GET, DealWithProfilePicture);
return;
}
Image UserAvatar = UIFBAvatar.GetComponent<Image>();
UserAvatar.sprite = Sprite.Create (result.Texture, new Rect (0,0,128, 128), new Vector2 (0,0));
}
void DealWiththeUserName (FBResult result)
{
if (result.Error != null)
{
Debug.Log ("Problem with getting user name");
FB.API ("/me?field=id,first_name",Facebook.HttpMethod.GET, DealWiththeUserName);
return;
}
profile = Util.DeserializeJSONProfile(result.Text);
Text UserMsg = UIFUserName.GetComponent<Text>();
UserMsg.text = "Hello, " + profile["first_name"];
}
public void ShareWithFriends()
{
FB.Feed (
linkCaption: "I'm Playing this awesome game check it out!",
picture: "http://stormyx.com/MyGameIcon.png",
linkName: "Come join me in this game now!",
link: "http://app.facebook.com/" + FB.AppId + "/?challenge_brag=" + (FB.IsLoggedIn ? FB.UserId : "guest")
);
}
public void InviteFriends()
{
FB.AppRequest
(
message: "This game is Fantastic!, join me now!",
title: "Invite your friends to join you"
);
}
public void FriendsScore()
{
FB.API ("/app/scores?fields=score,user.limit(30)", Facebook.HttpMethod.GET,ScoresCallback);
}
private void ScoresCallback (FBResult result)
{
Debug.Log ("Scores callback: " + result.Text);
scoresList = Util.DeserializeScores (result.Text);
foreach(Transform child in ScoreScrollList.transform)
{
GameObject.Destroy(child.gameObject);
}
foreach(object score in scoresList)
{
var entry = (Dictionary<string,object>) score;
var user = (Dictionary<string,object>) entry ["user"];
GameObject ScorePanel;
ScorePanel = Instantiate (ScoreEntryPanel) as GameObject;
ScorePanel.transform.parent = ScoreScrollList.transform;
Transform ThisScoreName = ScorePanel.transform.Find ("FriendName");
Transform ThisScoreScore = ScorePanel.transform.Find ("FriendScore");
Text ScoreName = ThisScoreName.GetComponent<Text>();
Text ScoreScore = ThisScoreScore.GetComponent<Text>();
ScoreName.text = user["name"].ToString();
ScoreScore.text = entry["score"].ToString();
ScoreName.text = user["name"].ToString();
ScoreScore.text = entry["score"].ToString();
Transform TheUserAvatar = ScorePanel.transform.Find ("FriendAvatar");
Image UserAvatar = TheUserAvatar.GetComponent<Image>();
FB.API (Util.GetPictureURL(user["id"].ToString(), 128,128), Facebook.HttpMethod.GET,delegate(FBResult pictureResult)
{
if(pictureResult.Error != null)
{
Debug.Log (pictureResult.Error);
}
else
{
UserAvatar.sprite = Sprite.Create (pictureResult.Texture, new Rect (0,0,128, 128), new Vector2 (0,0));
}
});
}
}
public void MyScore()
{
var scoreData = new Dictionary<string,string>();
scoreData ["score"] = (score).ToString();
FB.API ("/me/scores", Facebook.HttpMethod.POST, delegate(FBResult result)
{
Debug.Log ("Score submit result: " + result.Text);
}, scoreData);
}
public void StartGame ()
{
PlayerPrefs.SetInt("CurrentPlayerScore",0);
Application.LoadLevel (1);
}
public void Quit ()
{
Application.Quit ();
}
}

playing sound in unity when detect multiple image target

i detect more than one image target in #unity when i detect target i play a sound that pronounce the image target name. if i detect one target it play the sound loud but when detect multiple target it play one of sound loud and play the others very low or does not play them.
please i want specific way to do this in tutorial or explain that in your answer .
using UnityEngine;
public class SoundPlay: MonoBehaviour,ITrackableEventHandler
{
#region PRIVATE_MEMBER_VARIABLES
private TrackableBehaviour mTrackableBehaviour;
public AudioClip sound;
#endregion // PRIVATE_MEMBER_VARIABLES
#region UNTIY_MONOBEHAVIOUR_METHODS
void Start()
{
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
{
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
}
#endregion // UNTIY_MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
/// <summary>
/// Implementation of the ITrackableEventHandler function called when the
/// tracking state changes.
/// </summary>
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED)
{
OnTrackingFound();
}
else
{
OnTrackingLost();
}
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
private void OnTrackingFound()
{
Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);
// Enable rendering:
foreach (Renderer component in rendererComponents)
{
component.enabled = true;
}
// Enable colliders:
foreach (Collider component in colliderComponents)
{
component.enabled = true;
}
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");
GetComponentInChildren<fiveSound>().Play();
}
private void OnTrackingLost()
{
Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);
// Disable rendering:
foreach (Renderer component in rendererComponents)
{
component.enabled = false;
}
// Disable colliders:
foreach (Collider component in colliderComponents)
{
component.enabled = false;
}
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
}
public void Play(){
AudioSource.PlayClipAtPoint(sound, transform.position);
}
#endregion // PRIVATE_METHODS
}
Is 3D sound checked?
If it is then uncheck. Let me know how you get on!
^._.^
using UnityEngine;
using Vuforia;
public class SoundPlay: MonoBehaviour,ITrackableEventHandler
{
#region PRIVATE_MEMBER_VARIABLES
private TrackableBehaviour mTrackableBehaviour;
public AudioClip sound;
#endregion // PRIVATE_MEMBER_VARIABLES
#region UNTIY_MONOBEHAVIOUR_METHODS
void Start()
{
mTrackableBehaviour = GetComponent<TrackableBehaviour>();
if (mTrackableBehaviour)
{
mTrackableBehaviour.RegisterTrackableEventHandler(this);
}
}
#endregion // UNTIY_MONOBEHAVIOUR_METHODS
#region PUBLIC_METHODS
/// <summary>
/// Implementation of the ITrackableEventHandler function called when the
/// tracking state changes.
/// </summary>
public void OnTrackableStateChanged(
TrackableBehaviour.Status previousStatus,
TrackableBehaviour.Status newStatus)
{
if (newStatus == TrackableBehaviour.Status.DETECTED ||
newStatus == TrackableBehaviour.Status.TRACKED)
{
OnTrackingFound();
}
else
{
OnTrackingLost();
}
}
#endregion // PUBLIC_METHODS
#region PRIVATE_METHODS
private void OnTrackingFound()
{
Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);
// Enable rendering:
foreach (Renderer component in rendererComponents)
{
component.enabled = true;
}
// Enable colliders:
foreach (Collider component in colliderComponents)
{
component.enabled = true;
}
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " found");
GetComponentInChildren<AudioSource>().Play();
}
private void OnTrackingLost()
{
Renderer[] rendererComponents = GetComponentsInChildren<Renderer>(true);
Collider[] colliderComponents = GetComponentsInChildren<Collider>(true);
// Disable rendering:
foreach (Renderer component in rendererComponents)
{
component.enabled = false;
}
// Disable colliders:
foreach (Collider component in colliderComponents)
{
component.enabled = false;
}
Debug.Log("Trackable " + mTrackableBehaviour.TrackableName + " lost");
}
public void Play(){
AudioSource.PlayClipAtPoint(sound, transform.position);
}
#endregion // PRIVATE_METHODS
}