Quantcast
Channel: Questions in topic: "loadassetatpath"
Viewing all 62 articles
Browse latest View live

Importing Textures not working quite right with LoadAssetAtPath?

$
0
0

Hi All

Iam trying to import textures manually from a text file with the code:

Texture2D ImportTexture(string path)
{
     string destpath = System.IO.Directory.GetCurrentDirectory() + "/";

     System.IO.Directory.CreateDirectory(Path.GetDirectoryName(assetPath) + "/Textures");

     string assetpath = Path.GetDirectoryName(assetPath) + "/Textures/" + Path.GetFileName(path);

     File.Copy(path, destpath + assetpath, true);

     AssetDatabase.Refresh();
     return (Texture2D)AssetDatabase.LoadAssetAtPath(assetpath, typeof(Texture2D));
}

The problem being the textures get added and show up in Unity but the method LoadAssetAtPath returns a 'null' even though the texture is there, but oddly if I do a reimport then LoadAssetAtPath works fine and returns the Asset. Am I missing a step somewhere? Thanks Chris


Unexpected behaviour with LoadAssetAtPath

$
0
0
I am found this slightly annoying thing with LoadAssetAtPath when I create a prefab, and then attempt to link that prefab to another. This bit of code should explain what I'm doing... ---------- GameObject go = new GameObject(); go.AddComponent(); go.active = false; Object p = EditorUtility.CreateEmptyPrefab(myGameObjectPrefabPath); EditorUtility.ReplacePrefab(go, p, ReplacePrefabOptions.ConnectToPrefab); GameObject.DestroyImmediate(go); // Do I need this? AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); currentPrefab.linkToMyGameObject = AssetDatabase.LoadAssetAtPath( myGameObjectPrefabPath, typeof(MyGameObject)) as MyGameObject; EditorUtility.SetDirty(currentPrefab); ---------- I am generating a prefab in code, and assigning it to another prefab, to automate some tedious steps in setting things up. Everything works as intended, however, an instance of the prefab containing MyGameObject is created in the scene. Is this expected behaviour, and if so, how can I destroy the object which is created? The line which seems to create the object is LoadAssetAtPath. Is there any way to get a pointer to this object, or stop it from creating it in the first place?

ScriptableWizard Problem with LoadAssetAtPath

$
0
0
I'm getting error messages when trying to use this bit of code in a C# editor script - ScriptableWizard. The code is from the Unity script reference for "EditorUtility.InstantiatePrefab" I'm new to scripting, especially for the editor, so not sure how to solve this. Part of my code: string localPath = "Assets/Prefabs/prefab_" + prefab.name.ToLower() + ".prefab"; line 69 if (AssetDatabase.LoadAssetAtPath( localPath, GameObject)) { if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No")) { Debug.Log("File does exist already"); } } else { Debug.Log("File didn't exist already"); } **Errors in Unity**: Assets/Editor/CreatePrefabFromModels.cs(69,63): error CS0119: Expression denotes a `type', where a `variable', `value' or `method group' was expected Assets/Editor/CreatePrefabFromModels.cs(69,35): error CS1502: The best overloaded method match for `UnityEditor.AssetDatabase.LoadAssetAtPath(string, System.Type)' has some invalid arguments Assets/Editor/CreatePrefabFromModels.cs(69,35): error CS1503: Argument `#2' cannot convert `object' expression to type `System.Type'

AssetPostprocessor reference to asset being processed?

$
0
0
I wrote this class to streamline import settings on a bunch of UI textures. In addition to setting import settings, I want to create a material for each texture. This works great if I use "Reimport" from Unity after the textures have been imported, but upon the first automatic import, the material's texture is never set. It's as if:
(Texture2D)AssetDatabase.LoadAssetAtPath(assetPath,typeof(Texture2D));
returns null. Note that this is the only technique I could figure out in order to get a reference to the current asset being imported. It seems like there would be a built-in pointer to it, but I found nothing in the docs. Does anyone know why that would return null upon first import? Or if there is a better way to get a reference to the Texture2D that is being imported so I don't have to look it up using LoadAssetAtPath() ? [Edited the code to reflect the answer below.]

using UnityEngine;
using System.IO;
using System.Collections;
using UnityEditor;
public class UITextureImport : AssetPostprocessor
{
	void OnPreprocessTexture()
	{
		if (assetPath.Contains("Assets/Textures/UI/") && assetPath.Contains(".png"))
		{
			// Set specific properties for UI textures.
			TextureImporter textureImporter = (TextureImporter)assetImporter;
			textureImporter.textureType = TextureImporterType.Advanced;
			textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
			textureImporter.mipmapEnabled = false;
			textureImporter.filterMode = FilterMode.Point;
			textureImporter.wrapMode = TextureWrapMode.Clamp;
		}
	}
	void OnPostprocessTexture(Texture2D texture)
	{
		if (assetPath.Contains("Assets/Textures/UI/") && assetPath.Contains(".png"))
		{
			// Create a matching material if one doesn't exist.
			string materialPath = assetPath.Replace("Assets/Textures/UI/","Assets/Materials/UI/");			
			materialPath = materialPath.Substring(0,assetPath.LastIndexOf("/") + 1);
			if (!Directory.Exists(materialPath))
			{
				Directory.CreateDirectory(materialPath);
			}
			materialPath += "/" + Path.GetFileNameWithoutExtension(assetPath) + ".mat";
			Material material = (Material)AssetDatabase.LoadAssetAtPath(materialPath,typeof(Material));
			if (material == null)
			{
				// Material doesn't exist, so create it now.
				material = new Material(Shader.Find("UnlitAlphaImage"));
				material.mainTexture = texture;
				AssetDatabase.CreateAsset(material, materialPath);
			}
			else
			{
				// Material exists, so only assign the new texture to it.
				material.mainTexture = texture;
			}
		}
	}
}

Change material with EditorScript

$
0
0
I try to change the material of a gameobject in the editor by a EditorScript. I use this code: if(boolean == true) { var newMat = AssetDatabase.LoadAssetAtPath("Assets/blue.mat", typeof(Material)); if(newMat != null) Debug.Log("Asset loaded"); else Debug.Log("cant find asset"); target.renderer.material = newMat; } when i click the boolean in the EditorScript my debug log prints "Cant find asset".

Resources.LoadAssetAtPath not working in WebBuild

$
0
0
I'm using the following loop to grab files for an animation. This method makes it really easy for our artists to export animations from flash as PNG sequences. It works perfectly fine when run from within the unity editor. The files load and the animations play at the right time; however, when we build the project for the Web Player (this game will only be playable through a browser) the animations don't happen and I'm sure it's because of the *LoadAssetAtPath* function. Any Ideas? while (true) { string tempPath = PATH + mName + intToPaddedString(currentFrame, 4) + ".png"; tempTexture = null; tempTexture = Resources.LoadAssetAtPath(tempPath, typeof(Texture2D)); if (tempTexture == null) return; mTextures.Add(tempTexture as Texture2D); currentFrame++; }

AssetDatabase.LoadAssetAtPath() not working after any sort of project change.

$
0
0
I have created a class which holds data about an object, which looks like the following: using UnityEngine; using System.Collections; using System; using System.Collections.Generic; [Serializable] public class SerializedParameters : ScriptableObject { private SerializedParameter[] _items; public SerializedParameter[] Items { get { return _items; } set { _items = value; } } public SerializedParameters() { Items = new SerializedParameter[0]; } public bool Contains(string name) { for(int i = 0; i < Items.Length; i++) { if(Items[i].Name == name) { return true; } } return false; } public object GetValue(string name) { if(Contains(name)) { for(int i = 0; i < Items.Length; i++) { if(Items[i].Name == name) return Items[i].Value; } return null; } else { return null; } } public void AddParam(string name, object val) { SerializedParameter[] temp = new SerializedParameter[Items.Length + 1]; for(int i = 0; i < Items.Length; i++) { temp[i] = Items[i]; } temp[Items.Length] = new SerializedParameter(name, val); Items = temp; } } [Serializable] public class SerializedParameter { private string _name; private object _value; public string Name { get { return _name; } set { Debug.Log ("Name Field changed: " + value); _name = value; } } public object Value { get { return _value; } set { Debug.Log ("Value Field changed: " + value); _value = value; } } public SerializedParameter(string name, object val) { Name = name; Value = val; Debug.Log ("Constructor Called: Name-" + name + " Value-" + val ); } public SerializedParameter() { Debug.Log ("Constructor Called"); } } The purpose of this is so that at run time, if the component does not exist on the object, I can perform a replace of the component and the metadata about the component (public fields, etc.) will be restored as well, so that I can load a scene at runtime and bring in the scripts as a dll resource. The serialize and deserialize functions look like this: using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; using System; [ExecuteInEditMode()] public class ComponentBase : MonoBehaviour { public virtual void Serialize() { SerializedParameters parameters = ScriptableObject.CreateInstance(); Type type = this.GetType(); foreach(FieldInfo info in type.GetFields()) { foreach(Attribute att in info.GetCustomAttributes(true)) { if(att.ToString().Contains("SerializableProperty")) { object obj = info.GetValue(this); //Debug.Log (info.Name + " " + obj ); parameters.AddParam(info.Name, obj); } } } ComponentManager cm = gameObject.GetComponent(); if(cm != null) { AssetDatabase.CreateAsset(parameters, "Assets/" + cm.GUID + ".asset"); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } } public virtual void Deserialize() { ComponentManager cm = gameObject.GetComponent(); SerializedParameters parameters = AssetDatabase.LoadAssetAtPath ("Assets/" + cm.GUID + ".asset", typeof (SerializedParameters)) as SerializedParameters; if(parameters != null) { Type type = this.GetType(); foreach(FieldInfo info in type.GetFields()) { foreach(Attribute att in info.GetCustomAttributes(true)) { if(att.ToString().Contains("SerializableProperty")) { if(parameters.Contains(info.Name)) { info.SetValue(this, parameters.GetValue(info.Name)); } } } } } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void Awake() { Deserialize(); } } As you can see, I use reflection to go through all of the fields, and for every field store a SerializedParameter into the array in my SerializedParameters object. The whole SerializedParameters object is then saved as an asset using a unique GUID. If the component is ever missing, I simply run the deserialize function and the component comes back repopulated correctly, so that the scripts can activly choose whether or not to use a class at runtime (like an external dll) or to use the scripts in the project folder. If I run serialize on all objects, and asset with their GUID pops up in the Project panel. Then I can delete the component, deserialize and all works like a charm. However, If any changes to the project are made, such as changing the directory of any script, changing any script contents, or restarting unity, the LoadAsset at path does not work correctly. The object comes back, the correct number of fields are there, and all of the name values of the SerializedParameter object are correctly assigned but the Value property of the SerializedParameter objects are all null. Thank you for your time to look at this problem.

LoadAssetAtPath

$
0
0
I cant get this to work right for some reason. I have tried Resources and AssetDatabase to run this from but keep getting a null object from it. This is in editor and not runtime. importPath shows up correctly but impObject returns a null object. Any ideas? var prefabPath : String = assetPath.Replace(".fbx", "Prefab.prefab"); var importPath : String = assetPath; Debug.Log(importPath); var impObject : GameObject = Resources.LoadAssetAtPath(importPath, GameObject) as GameObject; Debug.Log(impObject);

How to change the image (texture) of a GUITexture in C#.

$
0
0
I am making a game, and the player has multiple weapons, and I want to display which weapon is being used. I made two pictures to show which picture is being used. But I have no idea how to make it switch from one to another. I understand how to access the GUITexture, but I don't understand how to access the Texture that is in my assets folder. This is the code I am currently using, but I don't know what's going wrong. GameObject.Find("Weapon").guiTexture.texture = Resources.Load("sword") as Texture2D; The image is names "sword". If you find a URL to my problem, please link me to it, but I could not find an answer.

capturing screen shot, and showing the captured image on screen

$
0
0
Hiii everyone, I have the requirement of capturing screen shot, saving it and accessing to show it on screen. How can I do this? please help out this new bee.... Thanks in advance

Loading texture2d by script null instance

$
0
0
Im trying to load a texture2d with c# at Start() I've seen several instances about using Resources.Load but i wasn't able to load it because i keep getting this message that the texture has to be instantiated? NullReferenceException: Object reference not set to an instance of an object this is how im loading private Texture2D gameTitleTxt; void Start() { gameTitleTxt = (Texture2D)Resources.Load("Textures/Gui/menu_design"); } what am I doing wrong?

I cannot load an asset in web player with instantiate

$
0
0
Hi i a very new to unity, I have a problem with instantiate in web build. I cannot load an object in web player. When i try to load it in editor it loads perfectly. This is the code that i use if (Application.isEditor) { assetPath = "file:///" + Application.streamingAssetsPath + "/" + thumb + goniakos + "_" + width + length + ".unity3d"; var eee = Application.streamingAssetsPath + "/" + thumb + goniakos + "_" + width + length + ".unity3d"; } else { message += " isNotEditor"; assetPath = Application.dataPath + "/StreamingAssets" + "/" + thumb + goniakos + "_" + width + length + ".unity3d"; eee = Application.dataPath + "/StreamingAssets" + "/" + thumb + goniakos + "_" + width + length + ".unity3d"; } message += assetPath; var www = new WWW(assetPath); var instance : GameObject = Instantiate(www.assetBundle.mainAsset); message += " isNotEditor"; thumb, width, and length are variables When i print the variable assetPath its a valid http address but the object doesent load Thank you

Loading Resources not working? Resources.LoadAll

$
0
0
In my Unity project, I have a single "Advanced- Sprite" which is the file, in this folder: Assets/Resources/Characters/HumanMale/HumaneMale.png The file is a Sprite, set to Sprite Mode: Multiple. I have an array, public Sprite[] characterSprites; Yet when it starts, the Array is empty, most likely bc the resources aren't being loaded by: String assetPath = "Characters/HumanMale/HumaneMale"; Sprite[] characterSprites = Resources.LoadAll (assetPath); I have tried all kinds of variations of the assetPath, and none seem to be working.

How to implement Live In game billboard ads

$
0
0
Hey Friends, I am new to unity. and I have assigned with the work to make in game live billboards ads. By live I mean on every time we play game we can have a different ad. Can anyone plz guide me on this issue. your help and thoughts would be highly appreciated. Thanks

Android texture AssetBundles loading problem

$
0
0
hi everyone, I'm trying to load images from an assetbundles but when I load the texture in the scene the image appear broken, I post the link at the file that I used to see if the problem is caused from some picture settings: http://dev.x-project.it/bundles/AssetsTest.zip In the file in the resources folder you can find the original image that i use for create the bundles. I'd like to know if the script that I use for export the bundles for the different device is correct, i post it below. I cant load the bundle in the editor mode and i don't understand where is the mistake, you can find the script in the "app" gameobject, maybe is only a wrong path setting but i've tried all the possibilities and it doesn't works. Another big problem is when i execute the "build and run" on Android device (Galaxy Tab 2) the application crashes immediately. in most cases the application when start, immediately minimize in the task bar so i have to reopen it again, sometimes more than one time before it works. On WebPlayer everything works fine. Any suggestion? Thanks in advance using UnityEngine; using System.Collections; public class ExampleLoadingBundle : MonoBehaviour { public GUIText label; public GUIText urlLabel; public GUITexture pic; public string url; // URL AssetBundle public int version = 1; // AssetBundle version public string assetName; // Name of the Asset to be loaded from the AssetBundle public string assetPath; // Path to the Asset in the Project folder Object ObjInstance; // Instance of the object string deviceFolder; GameObject obj; Texture2D texture; GameObject objects; void Awake(){ #if UNITY_WEBPLAYER deviceFolder = "webplayer"; #endif #if UNITY_ANDROID deviceFolder = "android"; #endif url = "http://dev.x-project.it/bundles/" + deviceFolder + "/compositions2.unity3d"; urlLabel.text = url; assetPath = "Assets/Resources/" + deviceFolder + "/compositions.unity3d"; } void Start(){ StartCoroutine(Download()); } IEnumerator Download () { AssetBundleLoader assetBundleLoader = new AssetBundleLoader (); yield return StartCoroutine(assetBundleLoader.LoadBundle (url, version, assetName, assetPath)); if (assetBundleLoader.Obj != null) { texture = Instantiate (assetBundleLoader.Obj) as Texture2D; pic.texture = texture; //pic.pixelInset.x label.text = pic.name + " -- " + pic.pixelInset; Debug.Log (label.text); } else { label.text = " Load failed!"; Debug.Log (label.text); } } }

Load gameobjects in-game

$
0
0
Hello. I would like to know, how to make the models (paint texture, trees, grass, ...) show up in a list in an in-game editor to choose from and then be able to place and position them on the map. Most important part, how to load/add them (I probably can manage the list and placing). Maybe it would be also good to see the borders (or mesh) of the object on the cursor when picking one model so placing can be more precise. It will be for an in-game map editor. Thanks.

LoadAssetAtPath() returning null IN EDITOR

$
0
0
Hello, I've searched and searched and mostly find people trying to use it for runtime stuff with builds and getting null. Well, I'm getting null from within the editor. **No play mode involved**. I have a static class which is used by a custom EditorWindow class. Everything in my editor works fine as far as saving, editing, etc. Except for loading in a prefab. I have tried AssetDatabase and Resources. And both the typed and untyped versions of the Resources function. I also tried LoadMainAssetAtPath(). Have tried both with and without the .prefab extension. Have tried the full path, even the path without "Assets". Everything returns null. I'm actually using the OpenFilePanel to get the path but have hardcoded it to be sure the path is indeed correct and for a better example. I've tried every suggestion and everything I can think of and am hoping someone can tell me what's up. The one thing I haven't tried, and I'm sure would work. Is a Resources folder and Resources.Load(). But I don't want or need these prefabs loaded or bundled at run time so LoadAssetAtPath() seems like exactly what I need but I can't make it work. Unity Consoles 4.3.4f1 GameObject temp1 = Resources.LoadAssetAtPath("Assets/[DragonBuilder]/NewDragon.prefab"); GameObject temp2 = (GameObject)Resources.LoadAssetAtPath("Assets/[DragonBuilder]/NewDragon.prefab", typeof(GameObject)); GameObject temp3 = (GameObject)AssetDatabase.LoadMainAssetAtPath("Assets/[DragonBuilder]/NewDragon.prefab"); Debug.Log(temp1); Debug.Log(temp2); Debug.Log(temp3); http://docs.unity3d.com/ScriptReference/Resources.LoadAssetAtPath.html http://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetAtPath.html Thanks!

Importing Textures not working quite right with LoadAssetAtPath?

$
0
0

Hi All

Iam trying to import textures manually from a text file with the code:

Texture2D ImportTexture(string path)
{
     string destpath = System.IO.Directory.GetCurrentDirectory() + "/";

     System.IO.Directory.CreateDirectory(Path.GetDirectoryName(assetPath) + "/Textures");

     string assetpath = Path.GetDirectoryName(assetPath) + "/Textures/" + Path.GetFileName(path);

     File.Copy(path, destpath + assetpath, true);

     AssetDatabase.Refresh();
     return (Texture2D)AssetDatabase.LoadAssetAtPath(assetpath, typeof(Texture2D));
}

The problem being the textures get added and show up in Unity but the method LoadAssetAtPath returns a 'null' even though the texture is there, but oddly if I do a reimport then LoadAssetAtPath works fine and returns the Asset. Am I missing a step somewhere? Thanks Chris

Unexpected behaviour with LoadAssetAtPath

$
0
0
I am found this slightly annoying thing with LoadAssetAtPath when I create a prefab, and then attempt to link that prefab to another. This bit of code should explain what I'm doing... ---------- GameObject go = new GameObject(); go.AddComponent(); go.active = false; Object p = EditorUtility.CreateEmptyPrefab(myGameObjectPrefabPath); EditorUtility.ReplacePrefab(go, p, ReplacePrefabOptions.ConnectToPrefab); GameObject.DestroyImmediate(go); // Do I need this? AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); currentPrefab.linkToMyGameObject = AssetDatabase.LoadAssetAtPath( myGameObjectPrefabPath, typeof(MyGameObject)) as MyGameObject; EditorUtility.SetDirty(currentPrefab); ---------- I am generating a prefab in code, and assigning it to another prefab, to automate some tedious steps in setting things up. Everything works as intended, however, an instance of the prefab containing MyGameObject is created in the scene. Is this expected behaviour, and if so, how can I destroy the object which is created? The line which seems to create the object is LoadAssetAtPath. Is there any way to get a pointer to this object, or stop it from creating it in the first place?

Loading an asset bundle is null on second load

$
0
0
Hi, I use the following code to load an asset bundle from disk: AssetBundle.CreateFromFile(path); This works first time I run this code, but if I try to load the same asset bundle later (while the instance of unity is running), the object is just NULL. I think this is because unity has maybe cached this in memory - if so, how do I access it second time round? Thanks in advance for any pointers!
Viewing all 62 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>