changing rigidbody.mass value in unity 3 D - unity3d

I am trying to change mass of a 3D object programmatically. But the object doesn't get the calculated mass but a 0 value initially. When the prefab of the object is created it gets the calculated mass of the previous object not the current mass. And the scenario repeats for all the prefabs created henceforth. How can I get around this problem? Any help is greatly appreciated.

You're probably missing a get component call:
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public float mass;
public Rigidbody rb;
void Start() {
rb = GetComponent<Rigidbody>();
rb.mass = 0.5f;
}
}

To give your rigidbody a mass can use the following script wise
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
void Example() {
rigidbody.mass = 0.5F;
}
}
Next time do some more research.
http://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-mass.html
Google first hit.

Related

The game object does not have a script attached to it

- error message
After completing the bullet script operation, I tried to insert the script into Bullet Sprite in 2D Object format, but an error was displayed and the insertion was not possible. I tried turning off and on the editor because I thought it was a bug because I had the same file name and class name, but it didn't work. Do you happen to know about this problem? The editor version is 2021.3.11f1.
Bullet Script
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Pool;
public class Bullet : MonoBehaviour
{
[SerializeField]
private float speed = 10f;
private IObjectPool<Bullet> pool;
void Update()
{
transform.Translate(Vector2.up);
}
public void SetPool(IObjectPool<Bullet> bulletPool)
{
Launcher.Instance.bulletPool = pool;
}
private void OnBecameInvisible()
{
Launcher.Instance.bulletPool.Release(this);
}
}
I turned off and on the editor and changed the class name because I thought it was different.

Why my NavMesh agents does not work after build?

My agents do a great job in the editor for avoiding static and dynamic obstacles(carving) and finishing the platform but after I build it and they only stay where they are and they rotate some random locations different for each one.
EDIT: I added a lineRenderer to show the path and it does not show up in the build even though they are created in the editor. Why would they stop path finding?
Here is my OpponentController class that only sets the finishLine as destination on awake:
using UnityEngine;
using UnityEngine.AI;
public class OpponentController : Competitor
{
[SerializeField] private NavMeshAgent agent;
[SerializeField] private Animator anim;
[SerializeField] private float _endPositionX = -23.54f;
void Awake()
{
//agent.speed = Random.Range(1.0f, 2.0f);
_startPosition = transform.position;
Vector3 endPosition = new Vector3(GameManager.instance.finishLine.position.x, 0, Random.Range(_limitZ, _limitZ));
agent.SetDestination(endPosition);
}
}
and Competitor is just a MonoBehaviour that I created as a base class :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Competitor : MonoBehaviour
{
protected Vector3 _endPosition;
protected float _limitZ;
public Vector3 _startPosition;
public void StartOver()
{
transform.position = _startPosition;
}
}
How can I fix this? It was a case study for a job application and I got only one day to make it work.
SOLUTION: I enabled carving for dynamic obstacles and made the NavMesh Surface change every time obstacles move their positions. It is an expensive job to do under low performance. Also, I learned that there is a performance bottleneck between editor and build. So disabling carving for some of the obstacles and trusting on obstacle avoidance of agents solved this problem. This guide helped me solve the situation.

Falling object gravity interval of time

I made this code where I have 8 objects and each object has this script, where between a random time interval the objects drop randomly
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cylinderFallv2 : MonoBehaviour
{
private Rigidbody temp;
// Start is called before the first frame update
void Start()
{
temp = GetComponent<Rigidbody>();
StartCoroutine(waitTime());
}
public IEnumerator waitTime() {
temp.useGravity = false;
float wait_time = Random.Range (3.0f;, 12.0f;);
yield return new WaitForSeconds(wait_time);
temp.useGravity = true;
}
}
what he intended was for the objects to fall one by one with an interval between them in a random order. any ideas?
If you want to control several objects, and they have some relation to each other, it is usually best to have one script on any GameObject, and let that script handle the other objects. The following example script can be placed on any GameObject.
using System.Collections;
using System.Linq;
using UnityEngine;
public class RandomFall : MonoBehaviour
{
public Rigidbody[] rigidbodies;
public float minTime = 3.0f;
public float maxTime = 12.0f;
private void Start()
{
foreach (Rigidbody rigidbody in rigidbodies)
rigidbody.useGravity = false;
StartCoroutine(dropRandomly());
}
public IEnumerator dropRandomly()
{
foreach (var rigidbody in rigidbodies.OrderBy(r => Random.value))
{
float wait_time = Random.Range(minTime, maxTime);
Debug.Log($"Waiting {wait_time:0.0} seconds...");
yield return new WaitForSeconds(wait_time);
Debug.Log($"Dropping {rigidbody.name}...");
rigidbody.useGravity = true;
}
Debug.Log("All dropped!");
}
}
You then have to add references to the objects you want to drop in the scene editor. It should look something like this (I have added four cylinders). Note that the objects you try to add must of course already have a Rigidbody component on them.

Unity URP 2D light

I've recently discovered the URP and am developing a 2D game for fun. I added a global 2d light and set up some code to grab the light component, but unity keeps saying that light 2D does not exist. The error in unity is "error CS0246: The type or namespace name 'Light2D' could not be found". This is the code I have so far. I also followed a tutorial by Jimmy Vegas to grab the system time.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
public class DayNight : MonoBehaviour
{
public GameObject theDisplay;
public GameObject GL;
public int hour;
public int minutes;
public int totaltime;
private bool AM;
void Start()
{
totaltime = System.DateTime.Now.Hour;
hour = System.DateTime.Now.Hour;
minutes = System.DateTime.Now.Minute;
}
public void Night()
{
//change light settings
GL.GetComponent<Light2D>().Intensity = 0.4;
}
}
To reference the Light2D Component you need to add the UnityEngine.Experimental.Rendering.Universal namespace to your code.
Namespace Example:
...
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
public class DayNight : MonoBehaviour
{
...
}
If you get an Error you need to just continue and try to compile it, to see if it actually works.
After that is done you should be able to access the Light2D Component of your GameObject without any further troubles.
Calling Light2D Example:
public float nightvalue = 0.4f;
public void Night()
{
// Change light intensity to nightvalue.
GL.GetComponent<Light2D>().intensity = nightvalue;
}

Unity: Distance between two game-objects in the scene view

I am new to Unity and as I am creating my interface, I am trying to find what's the distance between two game objects. I know how to do in a C#/javascript script, however I am strugling to find this information in the scene view. Any key I could press while moving an object to see the distance to its neighbours ?
In a script, you can use Vector3.Distance between vector3 to get the distance between two points. Every gameObject has a position that is represented in a Vector3.
Below is a script example that shows you how it works. You just have to drag the script onto a gameObject in your scene and drag in the inspector another gameobject in your scene. The script should run even when your not in play mode because of the [ExecuteInEditMode].This way you will see the distanceBetweenObjects update in real time without actually having to hit play.
using UnityEngine;
[ExecuteInEditMode]
public class DistanceBetweenTwoObjects : MonoBehaviour
{
public GameObject obj;
public float distanceBetweenObjects;
private void Update()
{
distanceBetweenObjects = Vector3.Distance(transform.position, obj.transform.position);
Debug.DrawLine(transform.position, obj.transform.position, Color.green);
}
private void OnDrawGizmos()
{
GUI.color = Color.black;
Handles.Label(transform.position - (transform.position -
obj.transform.position)/2, distanceBetweenObjects.ToString());
}
}
The method OnDrawGizmos will draw text in between the 2 objects showing the distance value to help make it more user friendly.
There isn't any built-in functionality for this, but it's fairly trivial to add such a readout into the display using [ExecuteinEditMode], which causes scripts to run even when the game is not in play mode. This script, for example, should readout the distances on different axes and in total:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[ExecuteInEditMode]
public class EditorDistanceDisplay : MonoBehaviour
{
public GameObject target1;
public GameObject target2;
public float distanceX;
public float distanceY;
public float distanceZ;
public float distanceTotal;
void Start()
{
}
void Update()
{
Vector3 delta = target2.transform.position - target1.transform.position;
distanceX = delta.x;
distanceY = delta.y;
distanceZ = delta.z;
distanceTotal = delta.magnitude;
}
}