Generate new prefab using prefab after edit in runtime - c#

I have simple script and work perfect, but only runing in Unity Editor. I Try build for mobile, not complete and error build. i using Unity 2019.3.4.
Is there a subtitute "using UnityEditor" for mobile script.
I need script for mobile. Any idea for running in mobile.
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.Collections.Generic;
public class Prefabz : MonoBehaviour
{
public GameObject selObj;
void Update()
{
if (Input.GetMouseButtonDown(0))
{
CreatePrefab();
}
}
void CreatePrefab()
{
//GameObject[] selObjs = Selection.gameObjects;
string charName = selObj.name;
// duplicate
GameObject newInstance = Instantiate(selObj);
newInstance.name = charName;
// now replace the prefab
string prefabPath = "Assets/trideeScript/" + charName + ".prefab";
var existingPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
if (existingPrefab != null)
{
PrefabUtility.ReplacePrefab(newInstance, existingPrefab, ReplacePrefabOptions.ReplaceNameBased);
}
else
{
PrefabUtility.CreatePrefab(prefabPath, newInstance);
}
// delete dupe
DestroyImmediate(newInstance);
Debug.Log("Prefab'd " + charName + "! \"" + prefabPath + "\"");
}
}

UnityEditor namespace is not supported on any platform, except actually Editor. That's why all editor scripts must be placed inside "Editor" folder, and that's why it's a good practice to keep any editor-related stuff inside pre-processor directives #if UNITY_EDITOR

Related

Why doesn't Google Play Game authorization work in Unity?

I did everything right, I specified SHA1 in the Google API, Linked it all to Google Console, inserted resources and Web Client ID into Unity, but every time I try to log in, it writes "Canceled".
In LogCat I don't get errors, there are only:
*** [Play Games Plugin 0.11.01] 02.18.23 ERROR: Returning an error code
GooglePlayGames.OurUtils.PlayGamesHelperObject:Update()
Google Play services out of date for iae.perfectray.dogs. Reqires 21300000 but found 212621032
Here is the authorization code:
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Auth : MonoBehaviour
{
// Start is called before the first frame update
public Text text;
void Start()
{
PlayGamesPlatform.Activate();
PlayGamesPlatform.DebugLogEnabled = true;
}
public void Authh()
{
PlayGamesPlatform.Instance.Authenticate(ProccessAuth);
}
internal void ProccessAuth(SignInStatus status)
{
if(status == SignInStatus.Success)
{
text.text = "Status: Succesfull";
}
else
{
text.text = "Status: " + status;
}
}
I've already tried everything, nothing works(

can't be loaded because another AssetBundle with the same files is already loaded. error while loading different bundles

I've tried load asset bundles from URLs. When I load only single asset bundle, it works well. But if I try to load multiple asset bundles, Unity gives this error: The AssetBundle 'https://example.com/uc?export=download&id=1234567' can't be loaded because another AssetBundle with the same files is already loaded.
example code as follows
using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using TMPro;
public class sahnecagir : MonoBehaviour
{
public TextMeshProUGUI Log;
// Start is called before the first frame update
void Start()
{
StartCoroutine(LoadBundleFromUrl("https://example.com/uc?export=download&id=123456", 2, 0, (uint)Crc.Gifts));
}
IEnumerator LoadBundleFromUrl(string url, int tip, uint version, uint crc)
{
using (UnityWebRequest uwr = UnityWebRequestAssetBundle.GetAssetBundle(url, version, crc))
{
uwr.SendWebRequest();
while (!uwr.isDone)
{
if(tip == 1) Log.text = "Rooms loading " + (uwr.downloadProgress * 100).ToString("0") + "%";
else if(tip == 2) Log.text = "Gifts loading " + (uwr.downloadProgress * 100).ToString("0") + "%";
yield return null;
}
if (uwr.isNetworkError || uwr.isHttpError)
{
Debug.Log(uwr.error);
}
else
{
if (tip == 1)
{
MainConfig.Instance.RoomBgBundle = DownloadHandlerAssetBundle.GetContent(uwr);
}
else if (tip == 2)
{
MainConfig.Instance.GiftBundle = DownloadHandlerAssetBundle.GetContent(uwr);
}
}
if (uwr.isDone && tip == 1)
{
Log.text = "Rooms loading 100%";
StartCoroutine(LoadBundleFromUrl("https://example.com/uc?export=download&id=1234567", 2, 0, 0));
}
else
{
Log.text = "Gifts loading 100%";
}
yield return null;
}
}
}
In my case I've been trying to modify a bundle with different files but Unity refuses to load the two different files even if they have different names, a different structure, different files inside, nothing.
Opening the bundle in Notepad++ brings up what I assume to be a "container name" of CAB-a317cdbf067bab183d6dd12d870c1407 as an example. This is what Unity seems to be checking for to determine whether a bundle is "identical."
A simple find and replace to a different name and boom. The bundles load now.

Writing .txt file in android

I need help with a problem in our system. We are using unity and visual studio C# to create a mobile VR game using gaze controls only (no controller). We need to find a way to write debug logs into a text file and save to android internal storage. Thanks in advance for the help!!
That is our code below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine;
public class VRPlace : MonoBehaviour
{
...
void OnTriggerEnter(Collider other)
{
string path = "Assets/Resources/PlacesLog.txt";
StreamWriter testing = new StreamWriter(path, true);
if (other.gameObject.name == "Hospital")
{
GameObject otherObj = other.gameObject;
Debug.Log("Triggered to: " + otherObj);
}
testing.WriteLine(other.gameObject.name);
testing.Close();
}
}
here is a sample for saving a .txt file with StreamWriter.
class FileSaver
{
static void Main()
{
// Create a StreamWriter instance
StreamWriter writer = new
StreamWriter(Application.PersistentDataPath + "/droidlog.txt");
// This using statement will ensure the writer will be closed when no longer used
using(writer)
{
// Loop through the numbers from 1 to 20 and write them
for (int i = 1; i <= 20; i++)
{
writer.WriteLine(i);
}
}
}
}
this saves the numbers 1-20, you will want to fill in the blanks... good luck!

QR Code Scanner in Unity?

I am trying to get QRCode reader in unity that works on ios and Android.
Unity Zxing QR code scanner integration
Using above answer I Have added Vuforia (Working perfectly alone). then i also have added Zxing.unity.dll in plugins folder, then added this script to ARCamera in a scene.
using UnityEngine;
using System;
using System.Collections;
using Vuforia;
using System.Threading;
using ZXing;
using ZXing.QrCode;
using ZXing.Common;
[AddComponentMenu("System/VuforiaScanner")]
public class VuforiaScanner : MonoBehaviour
{
private bool cameraInitialized;
private BarcodeReader barCodeReader;
void Start()
{
barCodeReader = new BarcodeReader();
StartCoroutine(InitializeCamera());
}
private IEnumerator InitializeCamera()
{
// Waiting a little seem to avoid the Vuforia's crashes.
yield return new WaitForSeconds(1.25f);
var isFrameFormatSet = CameraDevice.Instance.SetFrameFormat(Image.PIXEL_FORMAT.RGB888, true);
Debug.Log(String.Format("FormatSet : {0}", isFrameFormatSet));
// Force autofocus.
var isAutoFocus = CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_CONTINUOUSAUTO);
if (!isAutoFocus)
{
CameraDevice.Instance.SetFocusMode(CameraDevice.FocusMode.FOCUS_MODE_NORMAL);
}
Debug.Log(String.Format("AutoFocus : {0}", isAutoFocus));
cameraInitialized = true;
}
private void Update()
{
if (cameraInitialized)
{
try
{
var cameraFeed = CameraDevice.Instance.GetCameraImage(Image.PIXEL_FORMAT.RGB888);
if (cameraFeed == null)
{
return;
}
var data = barCodeReader.Decode(cameraFeed.Pixels, cameraFeed.BufferWidth, cameraFeed.BufferHeight, RGBLuminanceSource.BitmapFormat.RGB24);
if (data != null)
{
// QRCode detected.
Debug.Log(data.Text);
}
else
{
Debug.Log("No QR code detected !");
}
}
catch (Exception e)
{
Debug.LogError(e.Message);
}
}
}
}
But it is still not detecting any QRCode. Is there any other way to do QRcode reading and writing except Zxing? or any working sample project you have?
I also tried to implement a QRCode Reader with Vuforia and XZing using almost the same code you used. For me it worked, but it took very very long to detect the QRCode.
When I used a Color32 array instead of cameraFeed.pixels it was much quicker:
GUI.DrawTexture(screenRect, webCamTexture, ScaleMode.ScaleToFit);
try
{
IBarcodeReader barcodeReader = new BarcodeReader();
var result = barcodeReader.Decode(webCamTexture.GetPixels32(),
webCamTexture.width, webCamTexture.height);
if (result != null)
{
Debug.Log("DECODED TEXT FROM QR: " + result.Text);
loadNewPoi(Convert.ToInt32(result.Text));
PlayerPrefs.SetInt("camera_enabled", Convert.ToInt32(false));
webCamTexture.Stop();
}
}
But in this example I was using a WebCamTexture instead of Vuforia.
Unluckily it isn't possible to get a Color32 array with GetPixels32() from the Vuforia camera.
Another option is to use the QRCodes as Image-Targets, but I have a lot of wrong detections doing this.
For me there is no fitting solution for XZing together with Vuforia at the moment.

Load file downloaded iOS app created in Unity

I'm trying to load a json file downloaded and saved in the persistentDataPath of an iOS device. The download and save works great. However I think I have big issues to load the file. In fact when I try to compile the project in Xcode I have some errors messages.
First here is my C# code :
using UnityEngine;
using System.Collections;
using System.IO;
using System.Net;
using UnityEngine.UI;
public class ReadJson : MonoBehaviour
{
public Text City;
public Text Temperature;
public Image Weather;
public Text WeatherUrl;
[System.Serializable]
public class CityInfo
{
public string name;
}
[System.Serializable]
public class CurrentCondition
{
public string date;
public string hour;
public int tmp;
public int wnd_spd;
public int wnd_gust;
public string wnd_dir;
public double pressure;
public int humidity;
public string condition;
public string icon;
public string icon_big;
}
[System.Serializable]
public class RootObject
{
public CityInfo city_info;
public CurrentCondition current_condition;
}
void Start () {
WebClient client = new WebClient();
File.Delete(Path.Combine (Application.persistentDataPath, "myjson.json"));
client.DownloadFile ("http://www.myjsonurl", Path.Combine (Application.persistentDataPath, "myjson.json"));
TextAsset asset = Resources.Load (Path.Combine (Application.dataPath + "/Documents", "myjson")) as TextAsset;
RootObject m = JsonUtility.FromJson<RootObject> (asset.text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
}
}
And now the xcode console :
2016-10-21 17:01:20.766001 json[1404:516674] [DYMTLInitPlatform] platform initialization successful
2016-10-21 17:01:20.929950 json[1404:516508] -> registered mono modules 0xb95f70
2016-10-21 17:01:21.356590 json[1404:516508] You've implemented -[<UIApplicationDelegate> application:didReceiveRemoteNotification:fetchCompletionHandler:], but you still need to add "remote-notification" to the list of your supported UIBackgroundModes in your Info.plist.
-> applicationDidFinishLaunching()
2016-10-21 17:01:21.452967 json[1404:516508] Metal GPU Frame Capture Enabled
2016-10-21 17:01:21.453369 json[1404:516508] Metal API Validation Enabled
-> applicationDidBecomeActive()
Init: screen size 750x1334
Initializing Metal device caps
Initialize engine version: 5.3.4f1 (fdbb5133b820)
UnloadTime: 1.705875 ms
Salut/var/mobile/Containers/Data/Application/51A2490E-94EB-4904-9F2E-112AD5632A98/Documents
(Filename: /Users/builduser/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineDebugBindings.gen.cpp Line: 37)
NullReferenceException: A null value was found where an object instance was required.
(Filename: currently not available on il2cpp Line: -1)
Setting up 1 worker threads for Enlighten.
Thread -> id: 19f17000 -> priority: 1
If someone has an idea. Thanks a lot in advance.
The problem with your code is on this line:
TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;
I don't think you understand how and when to use Resources.Load. If you want to use the Resources.Load function, you must create a special folder from the Editor. This folder should be at <ProjectDirectory>/Assets/Resources. You can only put/write stuff into this folder from the Editor. You can't do it after build on iOS. It becomes read only after you build it. This special folder can then be read with the Resources.Load function.
Replacing:
TextAsset asset = Resources.Load(Path.Combine(Application.dataPath + "/Documents", "myjson")) as TextAsset;
with
string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));
RootObject m = JsonUtility.FromJson<RootObject>(text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
Should solve your problem.
Another API that should not be using is WebClient. Unless you have a good reason to use that, you shouldn't. You should either use the WWW or UnityWebRequest(newer and recommended) API.
This is what your code should look like without WebClient:
void Start()
{
StartCoroutine(DownloadAndloadJson());
}
IEnumerator DownloadAndloadJson()
{
string url = "http://www.myjsonurl";
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.Send();
if (www.isError)
{
Debug.Log(www.error);
}
else
{
//Sucessfully downloaded the Json File
Debug.Log("Json: " + www.downloadHandler.text);
string jsonFile = www.downloadHandler.text;
//Delete old json file. Don't know why but this was in your original code
File.Delete(Path.Combine(Application.persistentDataPath, "myjson.json"));
//Save the downloaded data as File
File.WriteAllText(Path.Combine(Application.persistentDataPath, "myjson.json"), jsonFile);
//Load the downloaded data
string text = File.ReadAllText(Path.Combine(Application.persistentDataPath, "myjson.json"));
Debug.Log(text);
RootObject m = JsonUtility.FromJson<RootObject>(text);
City.text = m.city_info.name;
Temperature.text = (m.current_condition.tmp).ToString();
}
}
If you have problems please update to Unity 5.4. The UnityWebRequest API should be used for this and it was introduced in 5.3 but bugs were fixed in 5.4. You need using UnityEngine.Networking; to use UnityWebRequest.

Categories

Resources