Unity3d attach texture to the cube problems - c#

I have created a cube in the scene and I want to attach the texture to the cube by scripting.
The problem is there is no error of my code but The cube doesn't change after I press run in my program...
Here is my code
using UnityEngine;
using System.Collections;
public class testing : MonoBehaviour {
void start(){
Texture2D tex = (Texture2D)Resources.Load("BlueColorTex.png", typeof(Texture2D));
renderer.material.mainTexture = tex;
}
}

void start()
{
Texture2D tex = (Texture2D)Resources.Load("BlueColorTex", typeof(Texture2D));
renderer.material.mainTexture = tex;
}
Resources.Load does not use extensions. This is a common mistake.
Returns the asset at path if it can be found otherwise returns null.
Only objects of type T will be returned. The path is relative to any
Resources folder inside the Assets folder of your project,
extensions must be omitted.
from: http://docs.unity3d.com/ScriptReference/Resources.Load.html

Related

Save Object mesh in Assets/Convert Default Asset File to Mesh Asset

I am working on a project where I have a script that combines all the meshes of a gameobjects childs into one mesh while in edit mode. Now the problem is that even though I have managed to then save the mesh into my assets folder it is only saved as a default asset(blank white icon) and not as a mesh that I can then use for other things. Now I would like to know how to get it saved as a mesh asset. I think I could either somehow convert the default asset file to a mesh asset if that is possible, or I could directly save an objects mesh into the asset folder but I dont know if that's possible.
I would be very grateful if you could share code that I could use to do this(it doesnt have to be fance, it should just work).
Here is the code that I have currently:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
[ExecuteInEditMode]
[RequireComponent(typeof(MeshFilter))]
[RequireComponent(typeof(MeshRenderer))]
// Copy meshes from children into the parent's Mesh.
// CombineInstance stores the list of meshes. These are combined
// and assigned to the attached Mesh.
public class CombineMeshes : EditorWindow
{
[Header("References")]
public GameObject generateFromObject;
[MenuItem("Window/My/MeshGenerator")]
static void Init()
{
CombineMeshes window = (CombineMeshes)GetWindow(typeof(CombineMeshes));
}
private void OnGUI()
{
generateFromObject = (GameObject)EditorGUILayout.ObjectField(generateFromObject, typeof(GameObject), true);
if (GUILayout.Button("Generate"))
{
Generate();
}
}
void Generate()
{
MeshFilter[] meshFilters = generateFromObject.GetComponentsInChildren<MeshFilter>();
CombineInstance[] combine = new CombineInstance[meshFilters.Length];
int i = 0;
while (i < meshFilters.Length)
{
combine[i].mesh = meshFilters[i].sharedMesh;
combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
i++;
}
generateFromObject.transform.GetComponent<MeshFilter>().mesh = new Mesh();
generateFromObject.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
generateFromObject.transform.gameObject.SetActive(true);
Mesh mesh = generateFromObject.transform.GetComponent<MeshFilter>().mesh;
AssetDatabase.CreateAsset(mesh, "Assets/myAsset");
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(mesh));
AssetDatabase.SaveAssets();
}
}

Can't load prefab in Unity Editor

I am trying to make an [ExecuteInEditMode] script spawn game objects (linked to the same prefab) at specific positions right in the Editor so that I can quickly create different hexagon tile maps by just triggering booleans in the inspector. However, the Resources.Load() method cannot not find the prefab even though the path is correct and so I get the following error:
NullReferenceException: Object reference not set to an instance of an object.
Here is the code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[ExecuteInEditMode]
public class PositionChecker : MonoBehaviour
{
[SerializeField] float tileGap = 1.5f;
[SerializeField] GameObject tilePrefab; // alternatively tried dragging the prefab in the field in the inspector - it worked
[SerializeField] bool tileUpLeft;
GameObject tilesParent;
private void Awake()
{
tilesParent = GameObject.Find("All Tiles");
tilePrefab = Resources.Load("Assets/Prefabs/Tile.prefab") as GameObject;
}
// Update is called once per frame
void Update()
{
CheckForCreateTile();
}
private void CheckForCreateTile()
{
if (tileUpLeft)
{
tileUpLeft = false;
InstantiateTilePrefab(new Vector3(transform.position.x - 0.6f * tileGap, transform.position.y, transform.position.z - tileGap));
}
}
private void InstantiateTilePrefab(Vector3 vector3)
{
GameObject newTile = PrefabUtility.InstantiatePrefab(tilePrefab, tilesParent.transform) as GameObject;
Debug.Log(tilePrefab); // null
Debug.Log(tilesParent); // ok
Debug.Log(newTile); // Null
newTile.transform.position = vector3;
}
}
If I drag the prefab onto the serialized field of each created tile manually in the inspector instead of trying to load it, everything works fine.
The asset has to be in a "Resources" folder. So to solve your problem you can put "Tile.prefab" into the folder "Assets/Resources" and use the relative path: Resources.Load("Tile.prefab");
https://docs.unity3d.com/ScriptReference/Resources.Load.html
The file-path string automatically starts with "Resources/". So you shouldn't type that in. Also I don't think unity likes the file type in the string so don't type that in either. This works for me:
GameObject tilePrefab;
tilePrefab = Resources.Load<GameObject>("Prefabs/Tile");
GameObject tile = Instantiate(tilePrefab, Vector3.zero, Quaternion.identity);

Can't change imported blender object material color by script

I'm trying to apply a script that changes the material color when the cursor is on top of the object. Here's the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ChangeColor : MonoBehaviour {
public Color startColor;
public Color mouseOverColor;
bool mouseOver = false;
void OnMouseEnter(){
Debug.Log("START");
mouseOver = true;
GetComponent<Renderer>().material.SetColor("_Color",mouseOverColor);
Debug.Log("TESTE");
}
void OnMouseExit(){
mouseOver = false;
GetComponent<Renderer>().material.SetColor("_Color", startColor);
}
}
This code works perfectly when applied to a cube created with unity, but when I try to use it on a imported mesh, it doesn't work.
Here's an example of one of the imported objects where the script doesn't work:
Can someone help me understand how can I solve this?
Thank you
Your imported meshes don't have a collider yet which is required for the mouse detect.
Add one, for a simple mesh like a sphere just use a Sphere Collider.
Edit:
Also, you should usually store a reference if you need to access it frequently.
private Renderer rend;
private void Awake()
{
rend = GetComponent<Renderer>();
}

WebCamTexture crashes when I change the scene

I'm trying to display telephone camera in two scenes using WebCamTexture but when I load second scene in my android device the game crashes. I've created a plane (as a cinema screen) in front the camera and I've attached this script:
using UnityEngine;
using System.Collections;
public class CameraController : MonoBehaviour
{
public WebCamTexture mCamera;
public GameObject plane;
void Start ()
{
plane = GameObject.FindWithTag ("PlayerCam");
mCamera = new WebCamTexture ();
plane.GetComponent<Renderer>().material.mainTexture = mCamera;
mCamera.Play ();
}
}
In unity editor all works ok, but when I load second scene my android device crashes. Can anybody help me?
You need to destroy the WebCamTexture before loading another scene

unity3d - how to create a terrain from a c# script

I'm looking to create a piece of terrain in unity using only a script (c# preferably) to do this rather than the menu options on the editor. So far I only have this code below, but I don't know what to do next to get it to appear on the scene, can anyone help?
Thank you
using UnityEngine;
using System.Collections;
public class terraintest : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject terrain = new GameObject();
TerrainData _terraindata = new TerrainData();
terrain = Terrain.CreateTerrainGameObject(_terraindata);
}
// Update is called once per frame
void Update () {
}
}
Simply adding :
Vector3 position = ... //the ingame position you want your terrain at
GameObject ingameTerrainGameObject = Instantiate(terrain, position, Quaternion.identity);
should make the terrain appear ingame. The Instantiate method returns a reference to the gameobject spawned ingame, so if you later want to access it, you can use that reference.

Categories

Resources