I am attempting to create a new element for my unity project but I need unity to render my whole object as a UI object how do I make this happen. My current script thus far.
using UnityEditor;
using UnityEngine;
public class OptionSwitch : MonoBehaviour {
[MenuItem ("GameObject/UI/Switch")]
static void Switch(){
GameObject go = new GameObject("switch");
go.transform.parent = Selection.activeTransform;
go.transform.localPosition = Vector3.zero;
}
}
It will be a option switch with a button on either side of a textbox indicating the active option.
I did more research and came up with this code.
using UnityEditor;
using UnityEngine;
public class OptionSwitch : MonoBehaviour {
[MenuItem ("GameObject/UI/Switch")]
static void Switch(){
if (GameObject.Find ("Canvas") != null) {
// Define Components
GameObject Canvas = GameObject.Find("Canvas");
GameObject Switch = new GameObject("Switch");
GameObject Previous = new GameObject("Previous Button");
GameObject Next = new GameObject("Next Button");
GameObject Text = new GameObject("Textbox");
// Place Switch
Switch.transform.parent = Canvas.transform;
Switch.transform.localPosition = Vector3.zero;
// Place Previous Button
Previous.transform.parent = Switch.transform;
Previous.transform.localPosition = Vector3.zero;
// Place Text Field
Text.transform.parent = Switch.transform;
Text.transform.localPosition = Vector3.zero;
// Place Next Field
Next.transform.parent = Switch.transform;
Next.transform.localPosition = Vector3.zero;
}
}
}
You have have to find the Canvas GameObject first. The Canvas GameObject has Canvas component attached to it. So, you use FindObjectOfType to find the Canvas component. You can then then convert the instance of that Canvas script into a GameObject. The fix for your original code:
[MenuItem("GameObject/UI/Switch")]
static void Switch()
{
//Create new GameObject
GameObject go = new GameObject("switch");
//Find Canvas in the Scene
Canvas canvas = (Canvas)GameObject.FindObjectOfType(typeof(Canvas));
//Get Canvas GameObject
GameObject canvasGameObject = canvas.gameObject;
//Make the new GameObject child of the Canvas
go.transform.parent = canvasGameObject.transform;
go.transform.localPosition = Vector3.zero;
//Change the new GameObject Layer to UI
go.layer = 5; //Or go.layer = canvasGameObject.layer;
//Add Rect Transform to it
go.AddComponent<RectTransform>();
}
Related
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class spawningunits : MonoBehaviour
{
public static int amount1 = 100;
public static int amount2 = 200;
public GameObject ShadowWolf;
public GameObject Cannibal;
//public GameObject numberofunits1;
//public GameObject numberofunits2;
[SerializeField] private GameObject numberofunits1;
[SerializeField] private TMP_Text numberofunits2;
GameObject someObj;
private void Start(){
//numberofunits1.text = "200";
numberofunits2.text = "600";
Instantiate(numberofunits1, new Vector3(50, -1, -5), Quaternion.identity);
Instantiate(numberofunits2, new Vector3(45, -1, -5), Quaternion.identity);
Instantiate(ShadowWolf, new Vector3(56, -1, -5), Quaternion.identity);
ShadowWolf.SetActive(true);
Instantiate(Cannibal, new Vector3(-56, -1, -5), Quaternion.identity);
Cannibal.SetActive(true);
someObj = new GameObject("SomeObj");
numberofunits1.transform.parent = someObj.transform;
//GameObject someObj = new GameObject("SomeObj");
//someObj.AddComponent(numberofunits1);
//Vector3 pozycjacannibala = Cannibal.transform.position;
//Vector3 pozycjashadowwolfa = ShadowWolf.transform.position;
//numberofunits1.text = "200";
numberofunits2.text = "100";
}
void Update() {
//GameObject someObj = new GameObject("SomeObj");
//numberofunits1.transform.parent = someObj;
//Gameobject numberofunits1g = Gameobject.Find("numberofunits1g").GetComponent<GameObject>();
//Vector3 pozycjacannibala = Cannibal.transform.position;
//Vector3 pozycjashadowwolfa = ShadowWolf.transform.position;
//numberofunits1.transform.position = new Vector3(20,-1,-5);
numberofunits2.transform.position = new Vector3(Cannibal.transform.position.x,Cannibal.transform.position.y,Cannibal.transform.position.z);
numberofunits2.GetComponent<RectTransform>().localPosition += new Vector3(20,-1,-5);
//numberofunits1.GetComponent<RectTransform>().localPosition = new Vector3(-56,-1,-5);
//Vector3 poz = numberofunits1.transform.position;
//print(poz);
someObj.transform.position = new Vector3(Cannibal.transform.position.x,Cannibal.transform.position.y,Cannibal.transform.position.z);
//numberofunits1.transform.position = new Vector3(40, 12, -5);
//numberofunits1.anchoredPosition = new Vector2(20,-1);
//Vector3 poz = numberofunits1.transform.position;
//print(poz);
}
}
What I want to do is move text to a certain position (the text is a prefab, I'm using text mesh pro). The problem I get is that instantiation works correctly setting up the text in a desired position, however I cant seem to be able to move it later on. The code doesn't throw any errors and I even set a print function to see what position does the code display and the position is correct, but on the screen the text is still in the same place. The project is being created in 2d.
When moving UI elements you will need to use the RectTransform instead of the regular transform (however the regular transform will still work for world space ui).
For example you could use:
numberofunits1.GetComponent().anchoredPosition = new Vector2(20,-1);
if you really need the z position you can use:
numberofunits1.GetComponent().anchoredPosition3D = new Vector3(20,-1,-5);
You can find the documentation on RectTransform here:
https://docs.unity3d.com/ScriptReference/RectTransform.html
I also recommend using the TextMeshPro variable for the UI element you are trying to use. So in this case: TMP_Text.
So your variable declaration would become:
[SerializeField] private TMP_Text numberofunits1;
[SerializeField] private TMP_Text numberofunits2;
If you're trying to move the full set of UI it might be useful if you move the regular transform on the Canvas. However in that case the canvas needs to be World Space.
TextMeshPro doesn't contain transform component but rect transform so you need to chanage rect trasnform Or you can either create a gameObject like
[SerializeField] private GameObject numberofunits1;
[SerializeField] private GameObject numberofunits2;
GameObject someObj;
void Start(){
someObj = new GameObject("SomeObj");
numberofunits1.transform.parent = someObj;
}
void Update()
{
numberofunits1.text = "200";
numberofunits2.text = "100";
//Gameobject numberofunits1g = Gameobject.Find("numberofunits1g").GetComponent<GameObject>();
//Vector3 pozycjacannibala = Cannibal.transform.position;
//Vector3 pozycjashadowwolfa = ShadowWolf.transform.position;
numberofunits2.GetComponent<RectTransform>().localPosition += new Vector3(20,-1,-5) * Time.deltTime;
someObj.transform.position += new Vector3(Cannibal.transform.position.x,Cannibal.transform.position.y,Cannibal.transform.position.z) * Time.deltaTime;
Vector3 poz = numberofunits1.GetComponent<RectTransform>().localPosition.transform.position;
print(poz);
}
I am trying to create a Fruit Ninja style game on Unity 2D and I want to create a trail that follows where the player has "cut". I've tried to instantiate a "cut" object that contains the line renderer every time a user drags. However, the line renderer is not showing up. Can anyone correct any errors or suggest a new method?
public class CreateCuts : MonoBehaviour
{
public GameObject cut;
public float cutDestroyTime;
private bool dragging = false;
private Vector2 swipeStart;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragging = true;
swipeStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
}
else if (Input.GetMouseButtonUp(0) && dragging)
{
createCut();
}
}
private void createCut()
{
this.dragging = false;
Vector2 swipeEnd = Camera.main.ScreenToWorldPoint(Input.mousePosition);
GameObject cut = Instantiate(this.cut, this.swipeStart, Quaternion.identity) as GameObject;
cut.GetComponent<LineRenderer>().positionCount = 1 ;
cut.GetComponent<LineRenderer>().enabled = true;
cut.GetComponent<LineRenderer>().SetPosition(0, this.swipeStart);
cut.GetComponent<LineRenderer>().SetPosition(1, swipeEnd);
Vector2[] colliderPoints = new Vector2[2];
colliderPoints[0] = new Vector2(0.0f, 0.0f);
colliderPoints[1] = swipeEnd - swipeStart;
cut.GetComponent<EdgeCollider2D>().points = colliderPoints;
Destroy(cut.gameObject, this.cutDestroyTime);
}
}
I expect there to be a line, but nothing shows up. There is also a warning stating that the SetPosition(1, swipeEnd) is out of bounds.
EDIT: Here are the settings of my cut object
1st part of cut object settings
2nd part of cut object settings
Positions tab of line renderer
I want to create a trail that follows where the player has "cut".
The word "trail" indicates that you should rather use a trail renderer!
Manual: https://docs.unity3d.com/Manual/class-TrailRenderer.html
API reference: https://docs.unity3d.com/ScriptReference/TrailRenderer.html
Back to your original question:
Your linerenderer probably is rendered but at a random position, because of Vector2 to Vector3 conversion, i dunno your project structure but this can be the case.
Please post a picture with one of your cut gameobject, that holds your linerenderer, and also extend the positions tab on the linerenderer so we can see your points xyz coordinates
Also apply the changes mentioned by commenters, because you really need 2 verticies for a line :P
Update:
public class CreateCuts : MonoBehaviour
{
public GameObject cut;
public float cutDestroyTime;
private bool dragging = false;
private Vector3 swipeStart;
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
dragging = true;
swipeStart = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("Swipe Start: " + swipeStart);
}
else if (Input.GetMouseButtonUp(0) && dragging)
{
createCut();
}
}
private void createCut()
{
this.dragging = false;
Vector3 swipeEnd = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("SwipeEnd: " + swipeEnd);
GameObject cut = Instantiate(this.cut, swipeStart, Quaternion.identity);
cut.GetComponent<LineRenderer>().positionCount = 2;
// why is it not enabled by default if you just instantiate the gameobject O.o?
cut.GetComponent<LineRenderer>().enabled = true;
cut.GetComponent<LineRenderer>().SetPositions(new Vector3[]{
new Vector3(swipeStart.x, swipeStart.y, 10),
new Vector3(swipeEnd.x, swipeEnd.y, 10)
// z is zero cos we are in 2d in unity up axis is Y we set it to 10 for visibility reasons tho}
});
// Commented out cos atm we are "debugging" your linerenderer
// Vector2[] colliderPoints = new Vector2[2];
// colliderPoints[0] = new Vector2(0.0f, 0.0f);
// colliderPoints[1] = swipeEnd - swipeStart;
// cut.GetComponent<EdgeCollider2D>().points = colliderPoints;
//Destroy(cut.gameObject, this.cutDestroyTime);
}
}
I keep getting the error:
NullReferenceException: Object reference not set to an instance of an object
which brings me to the line:
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, enemy.groundCheckDistance))
I did some testing and found out that the enemy was in fact set to the instance of this object because I printed the value for enemy.groundCheckDistance every update and it successfully printed the correct value from the from the enemy object every time. I even changed it in the inspector and it retrieved the correct value. I later discovered that all of the objects I set in the Start() method are turning to null only outside of the Start() method. (By this I mean the Animator, Rigidbody, Capsule Collider, etc. are turning null) I am 100% sure that an animator, capsule collider, rigidbody, and enemy are attached to this gameobject. However, I am creating them on Awake() in a different class. Could that be why I am getting the error? If it is how do I fix it?
This is the script where I add the components on Awake(). When I run the game I see that they have successfully been added.
using UnityEngine;
using UnityEngine.AI;
namespace MGCO.Characters.EnemyScripts
{
//USED TO CONSTRUCT THE COMPONENTS ON AN ENEMY AT RUNTIME
public class EnemyComponents : MonoBehaviour
{
//INITIALIZE ENEMY OBJECT
Enemy enemy;
void Awake()
{
enemy = GetComponent<Enemy>();
//MAKE SURE ENEMY IS NOT HUMANOID
if (!enemy.isHumanoid)
{
//CHECK TO SEE IF MESH FILTER ALREADY EXISTS
if (!GetComponent<MeshFilter>())
{
//INITIALIZE "MeshFilter"
MeshFilter meshFilter = gameObject.AddComponent<MeshFilter>();
//SET MESH OF MESHFILTER
meshFilter.mesh = enemy.enemyMesh;
}
//CHECK TO SEE IF MESH RENDERER ALREADY EXISTS
if (!GetComponent<MeshRenderer>())
{
//INITIALIZE "MeshRenderer"
MeshRenderer meshRenderer = gameObject.AddComponent<MeshRenderer>();
//SET MESH MATERIAL
meshRenderer.material = enemy.meshMaterial;
}
}
//MAKE SURE ENEMY IS NOT HUMANOID
else
{
//CHECK TO SEE IF ANIMATOR ALREADY EXISTS
if (!GetComponent<Animator>())
{
//INITIALIZE "RuntimeAnimatorController"
Animator animator = gameObject.AddComponent<Animator>();
//SET RUNTIMEANIMATORCONTROLLER
animator.runtimeAnimatorController = enemy.runtimeAnimatorController;
//SET AVATAR
animator.avatar = enemy.avatar;
//SET ROOT ANIMATION BOOL
animator.applyRootMotion = enemy.applyRootMotion;
}
}
//CHECK TO SEE IF RIGIDBODY ALREADY EXISTS
if (!GetComponent<Rigidbody>())
{
//INITIALIZE "Rigidbody"
Rigidbody enemyRigidbody = gameObject.AddComponent<Rigidbody>();
//SET MASS
enemyRigidbody.mass = enemy.mass;
//SET DRAG
enemyRigidbody.drag = enemy.drag;
//SET ANGULAR DRAG
enemyRigidbody.angularDrag = enemy.angularDrag;
//SET USE GRAVITY
enemyRigidbody.useGravity = enemy.useGravity;
}
//CHECK TO SEE IF NAVMESHAGENT ALREADY EXISTS
if (!GetComponent<NavMeshAgent>())
{
//INITIALIZE "NavMeshAgent"
NavMeshAgent navMeshAgent = gameObject.AddComponent<NavMeshAgent>();
//SET NAVMESH SPEED
navMeshAgent.speed = enemy.speed;
//SET BASE OFFSET
navMeshAgent.baseOffset = enemy.baseOffset;
//SET ANGULAR SPEED (HOW FAST ENEMY TURNS CORNERS)
navMeshAgent.angularSpeed = enemy.angularSpeed;
//SET ACCELERATION
navMeshAgent.acceleration = enemy.acceleration;
//SET STOPPING DISTANCE
navMeshAgent.stoppingDistance = enemy.stoppingDistance;
//SET OBSTACLE AVOIDANCE RADIUS
navMeshAgent.radius = enemy.navmeshRadius;
//SET OBSTACLE AVOIDANCE HEIGHT
navMeshAgent.radius = enemy.navmeshHeight;
}
//CHECK TO SEE IF COLLIDER ALREADY EXISTS
if (!GetComponent<CapsuleCollider>())
{
//INITIALIZE "CapsuleCollider"
CapsuleCollider capsuleCollider = gameObject.AddComponent<CapsuleCollider>();
//SET CENTER
capsuleCollider.center = enemy.center;
//SET COLLIDER RADIUS
capsuleCollider.radius = enemy.colliderRadius;
//SET COLLIDER HEIGHT
capsuleCollider.height = enemy.colliderHeight;
}
}
}
}
This is the script that gets the error:
using UnityEngine;
namespace MGCO.Characters.EnemyScripts
{
public class EnemyAnimation : MonoBehaviour
{
//REFERENCE GAMEOBJECTS
Enemy enemy;
Animator animator;
Rigidbody enemyRigidbody;
CapsuleCollider capsuleCollider;
//INITIALIZE VARS
Vector3 groundNormal;
Vector3 capsuleCenter;
private bool isCrouching;
private bool isGrounded;
private float originalGroundCheckDistance;
private float turnAmount;
private float forwardAmount;
private float capsuleHeight;
//VALUE FOR HALF (NEVER CHANGES)
const float half = 0.5f;
//RUNS ON START
void Start()
{
enemy = GetComponent<Enemy>();
animator = GetComponent<Animator>();
enemyRigidbody = GetComponent<Rigidbody>();
capsuleCollider = GetComponent<CapsuleCollider>();
capsuleHeight = capsuleCollider.height;
capsuleCenter = capsuleCollider.center;
//FREEZE RIGIDBODY ROTATION
enemyRigidbody.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationY | RigidbodyConstraints.FreezeRotationZ;
//SET LOCAL VARIABLE
originalGroundCheckDistance = enemy.groundCheckDistance;
}
...
//CHECKS POSITION OF GROUND BENEATH PLAYER
void CheckGroundStatus()
{
//INITIALIZE RAYCASTHIT
RaycastHit hitInfo;
//IF RAYCASTS DOWN TO "GroundCheckDistance" VARIABLE
if (Physics.Raycast(transform.position + (Vector3.up * 0.1f), Vector3.down, out hitInfo, enemy.groundCheckDistance))
{
//SET GROUNDNORMAL TO THE SURFACE OF THE RAYCASTHIT
groundNormal = hitInfo.normal;
//SET JUMPING FALSE
isGrounded = true;
//ANIMATOR APPLY ROOT MOTION
animator.applyRootMotion = true;
}
else
{
//SET JUMPING TO TRUE
isGrounded = false;
//SET GROUNDNORMAL TO GO UP
groundNormal = Vector3.up;
//ANIMATOR DO NOT APPLY ROOT MOTION
animator.applyRootMotion = false;
}
}
}
}
And thank you for your help :)
//REFERENCE GAMEOBJECTS
Enemy enemy;
Animator animator;
Rigidbody enemyRigidbody;
CapsuleCollider capsuleCollider;
Here you declare your references but you are not ASSIGNING them anywhere.
Rigidbody enemyRigidbody = gameObject.AddComponent<Rigidbody>();
Here, you add the rigidbody component and it returns a reference to itself. However, you assigned the reference to a DIFFERENT variable called enemyRigidbody instead of the one you declared above.
Even though the variable names are similar, declaring a variable within a smaller scope/declaration space (One within a class, another within a method) creates a ENTIRELY NEW variable with the same name but ONLY USABLE WITHIN THE METHOD ITSELF.
What you want is:
enemyRigidbody = gameObject.AddComponent<Rigidbody>();
which is a reference to the Rigidbody you declared above.
In my Unity project I would like to use the FastObjImporter class found on the internet to put obj on the scene. Do I have to create an empty GameObject and assign processed obj to it?
Try with an empty game object:
GameObject go = new GameObject("obj");
myMesh = FastObjImporter.Instance.ImportFile(objPath);
Instantiate(myMesh, Vector3.zero, Quaternion.identity);
go.AddComponent<MeshRenderer>();
go.GetComponent<MeshFilter>().mesh = myMesh;
Earlier I tried this way but it also did not work:
GameObject go;
myMesh = FastObjImporter.Instance.ImportFile(objPath);
Instantiate(myMesh, Vector3.zero, Quaternion.identity);
go.GetComponent<MeshFilter>().mesh = myMesh;
Could someone explain what I'm doing wrong?
CODE:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using System.IO;
/// <summary>
/// Sample
/// </summary>
public class DriveTest : MonoBehaviour
{
//public static readonly string REQUIRED_MIME = "image/jpeg";
//public string filePath;
public string objPath;
bool initInProgress = false;
GoogleDrive drive;
public string url;
List<GoogleDrive.File> remoteObjFiles;
public Mesh myMesh;
public GameObject go;
/* ---------------------------------------------------------------------------------------------------------------------------------- */
void Start()
{
objPath = Application.persistentDataPath + "/testObj.obj";
StartCoroutine(ImportObj());
go = new GameObject("obj");
}
/* ---------------------------------------------------------------------------------------------------------------------------------- */
void Update()
{
if (Input.GetKey(KeyCode.Escape))
Application.Quit();
}
/* ---------------------------------------------------------------------------------------------------------------------------------- */
IEnumerator ImportObj()
{
initInProgress = true;
drive = new GoogleDrive();
var driveInit = drive.Initialize();
while (driveInit.MoveNext())
yield return null;
initInProgress = false;
for (;;)
{
( SEARCHING AND SETTING DOWNLOAD FOLDER IN GDRIVE )
var download = drive.DownloadFile(remoteObjFiles[0]);
yield return StartCoroutine(download);
var data = GoogleDrive.GetResult<byte[]>(download);
if (File.Exists(objPath))
{
File.Delete(objPath);
File.WriteAllBytes(objPath, data);
}
else
File.WriteAllBytes(objPath, data);
Debug.Log("Obj: " + remoteObjFiles[0].ToString());
if (File.Exists(objPath))
{
Debug.Log("Loading OBJ from the device");
myMesh = FastObjImporter.Instance.ImportFile(objPath);
Debug.Log("Obj imported...");
Instantiate(myMesh, Vector3.zero, Quaternion.identity);
go.AddComponent<MeshRenderer>();
go.GetComponent<MeshFilter>().mesh = myMesh;
}
break;
}
}
Regards
There is no need to instantiate the Mesh. It is a component and I am not sure if you can even instantiate it. Just assign it to the material.
The main problem in your code is that you are not creating a material and a shader. You need to create a material, then create a "Standard" shader and assign that shader to the that material.
I noticed that the FastObjImporter script is old and decided to try it to make sure it is functioning properly. I ran into an index exception bug in it then fixed it. You can grab the copy of the fixed version here. See line #57 for the actual fix I made.
Functions to create MeshFilder, Material and MeshRenderer:
void attachMeshFilter(GameObject target, Mesh mesh)
{
MeshFilter mF = target.AddComponent<MeshFilter>();
mF.mesh = mesh;
}
Material createMaterial()
{
Material mat = new Material(Shader.Find("Standard"));
return mat;
}
void attachMeshRenderer(GameObject target, Material mat)
{
MeshRenderer mR = target.AddComponent<MeshRenderer>();
mR.material = mat;
}
Function to create new GameObject, load the model and attach every necessary components to it in order to display it:
GameObject loadAndDisplayMesh(string path)
{
//Create new GameObject to hold it
GameObject meshHolder = new GameObject("Loaded Mesh");
//Load Mesh
Mesh mesh = FastObjImporter.Instance.ImportFile(path);
//return null;
//Attach Mesh Filter
attachMeshFilter(meshHolder, mesh);
//Create Material
Material mat = createMaterial();
//Attach Mesh Renderer
attachMeshRenderer(meshHolder, mat);
return meshHolder;
}
Usage:
void Start()
{
string objPath = Application.persistentDataPath + "/testObj.obj";
GameObject obj = loadAndDisplayMesh(objPath);
//Position it in front od=f the camera. Your ZOffset may be different
Camera cam = Camera.main;
float zOffset = 40f;
obj.transform.position = cam.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, cam.nearClipPlane + zOffset));
}
EDIT:
In some rare cases, Unity cannot find the shader on Android when Shader.Find("Standard") is used. You get the error when that happens.
A work around for this would be to create a Material in the Editor and assign the "Standard" shader to it. It should use "Standard" shader by default.
1.Create a material and name is "StandardMat".
2.Put that material inside a folder called "Resources". Create it if it doesn't exist. You must spell this correctly. Again, the folder must be named "Resources" and placed inside the "Asset" folder.
3.You can load the material with Resources.Load("StandardMat") as Material.
In the createMaterial function above,
Change
Material mat = new Material(Shader.Find("Standard"));
to
Material mat = Resources.Load("StandardMat") as Material;
I'm trying to connect two GameObject (sphereObject0 and sphereObject2) with a line renderer lineRenderer0_2 in a Unity3D project.
The line shows up fine at first. My problem is that I need the line renderer to update its start and end positions to match the positions of sphereObject0 and sphereObject2.
For some reasons, my line renderer is absolutely static, and I can't find the way to make it adjust its start and end positions together with the spheres GameObjects eventually move around.
Here's my C# script, any idea about what I am doing wrong? Any help is greatly appreciated!
using UnityEngine;
using System.Collections;
public class autoCreateNetwork : MonoBehaviour {
public bool sphereHasGravity = false;
private Collider coll;
private Renderer rend;
private SpringJoint springJoint;
public Material lines;
GameObject sphereObject0;
GameObject sphereObject2;
LineRenderer lineRenderer0_2 ;
void Start () {
// Spawn a sphere and set it up
sphereObject0 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphereObject0.transform.position = new Vector3(-10.2571400951f, 98.8977277884f, -19.9870244083f);
Rigidbody sphereBody0 = sphereObject0.AddComponent<Rigidbody>();
sphereBody0.mass = 1f;
// Physics model
coll = sphereBody0.GetComponent<Collider> ();
PhysicMaterial material0 = new PhysicMaterial();
material0.dynamicFriction = 1;
coll.material = material0;
coll.material.bounciness = .8f;
// Render (color, smoothness, etc.)
rend = sphereBody0.GetComponent<Renderer>();
rend.material.color = new Color32(171,166,164,255);
rend.material.SetFloat("_Metallic", 0.0f);
rend.material.SetFloat("_Glossiness", 0.0f);
sphereBody0.useGravity = sphereHasGravity;
sphereBody0.transform.localScale = new Vector3(0.5f,0.5f,0.5f);
// Spawn a sphere and set it up
sphereObject2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
sphereObject2.transform.position = new Vector3(-28.1943570987f, 89.5665878403f, 5.43686642264f);
Rigidbody sphereBody2 = sphereObject2.AddComponent<Rigidbody>();
sphereBody2.mass = 1f;
// Physics model
coll = sphereBody2.GetComponent<Collider> ();
PhysicMaterial material2 = new PhysicMaterial();
material2.dynamicFriction = 1;
coll.material = material2;
coll.material.bounciness = .8f;
// Render (color, smoothness, etc.)
rend = sphereBody2.GetComponent<Renderer>();
rend.material.color = new Color32(105,150,187,255);
rend.material.SetFloat("_Metallic", 0.0f);
rend.material.SetFloat("_Glossiness", 0.0f);
sphereBody2.useGravity = sphereHasGravity;
sphereBody2.transform.localScale = new Vector3(0.5f,0.5f,0.5f);
// Spawn a line and set it up
GameObject line0_2 = new GameObject();
LineRenderer lineRenderer0_2 = line0_2.AddComponent<LineRenderer>();
lineRenderer0_2.material = lines;
lineRenderer0_2.widthMultiplier = 0.0482773661501f;
lineRenderer0_2.SetPosition(0, sphereObject0.transform.position);
lineRenderer0_2.SetPosition(1, sphereObject2.transform.position);
float alpha0_2 = .9f;
Gradient gradient0_2 = new Gradient();
gradient0_2.SetKeys(
new GradientColorKey[] { new GradientColorKey(new Color32(171,166,164,255), 0.0f), new GradientColorKey(new Color32(105,150,187,255), 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(alpha0_2, 0.0f), new GradientAlphaKey(alpha0_2, 1.0f) }
);
lineRenderer0_2.colorGradient = gradient0_2;
lineRenderer0_2.useWorldSpace = true;
}
void Update () {
lineRenderer0_2.SetPosition(0, sphereObject0.transform.position);
lineRenderer0_2.SetPosition(1, sphereObject2.transform.position);
}
}
Your issue is how you're assigning the LineRenderer with AddComponent to a new variable instead of your member variable. The line here:
LineRenderer lineRenderer0_2 = line0_2.AddComponent<LineRenderer>();
creates a new variable named lineRenderer0_2 within the scope of Start() and hides the member variable when referenced elsewhere in that function. Change the line to:
lineRenderer0_2 = line0_2.AddComponent<LineRenderer>();
and it should work fine. As a side-node, it's common to name member variables with an "m_" prefix so you don't run into these issues.