How can I access the Unity 'Light 2D (Script)' component via Script? - c#

In my Unity 2D game, I have a character with a lightsource component
'Light 2D(Script)' from the Lightweight RP package.
I want to change the intensity of the Light 2D with the code below.
But I can't assign the 'Light 2D(Script)' to the public Light LightSource in the Unity Inspector panel.
I've tried using public Light2D LightSource class but it doesn't seem to exist.
Is there any other way to access the 2D Light component or something I'm doing wrong?
I've also added a screenshot of the Inspector pane, if it helps.
If there's any more information you need just tell me and I hope someone can help. Thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Lighting : MonoBehaviour
{
public Light LightSource;
public float lightIntensity;
public float minIntensity = 0.35f, maxIntensity = 0.65f;
void Update()
{
lightIntensity = Random.Range(minIntensity, maxIntensity);
LightSource.intensity = lightIntensity;
}
}
Character Inspector Screenshot

Assuming you are using the universal render pipeline for 2D lighting this is the solution I found.
Within the Light2D script (which you can open by clicking the three vertical dots in the top right of the Light2D component and hitting edit script) there is the declaration of the namespace UnityEngine.Experimental.Rendering.Universal In order to reference Light2D simply at the top of your script write
using UnityEngine.Experimental.Rendering.Universal;
There may appear to be an error when doing this, but press on. From here on out you'll be able to reference the Light2D component much as you would any other component, such as using GetComponent<Light2D>() If any of this gives an error within your code editor still compile to test if it works, I have a fully functioning script using this method but Visual Studio still believes that Light2D does not exist. Regardless, this appears to work and I hope this works for everyone else as well.

Ok bud i got your answer.
First off, u need to open the Light2D(script) do the following:
1.) add the following to the top of the script:
using System.Collections;
using UnityEngine;
2.) you need to set the class of the Light2D script to "public" (so u can access it in your "lighting.cs" script.):
public class Light2DManager : IDisposable
3.) once that is done save the light2d script.
Ok now we are going to access it...
in your Lighting script we do the usual when we want to access another script:
GameObject TheLight = GameObject.Find("The Gameobject the script is on");
UnityEngine.Experimental.Rendering.LWRP.Light2D The2DLights = TheLight.GetComponent <UnityEngine.Experimental.Rendering.LWRP.Light2D> ();
Now you should have access, just type the following to confirm:
The2DLights. (and you will get options like intensity etc etc)
This is my first time ever answering a question. turns out i was having the same issue, happy to help.

Ran into this today, to expand on this solution of the using statement (simply adding it did not work in my case, on 2020.2) at the top you can do:
using Light2DE = UnityEngine.Experimental.Rendering.Universal.Light2D;
Then use Light2DE as the class instead of Light2D in your script.
light = transform.GetComponent<Light2DE>();

I don't understand the question very clearly, but it's possible you're just looking for "GetComponent".
Here's a random example,
public class CamToUI:MonoBehaviour
{
[System.NonSerialized] public WebCamTexture wct;
public Text nameDisplay;
private RawImage rawImage;
private RectTransform rawImageRT;
private AspectRatioFitter rawImageARF;
private Material rawImageMaterial;
void Awake()
{
rawImage = GetComponent<RawImage>();
rawImageRT = rawImage.GetComponent<RectTransform>();
rawImageARF = rawImage.GetComponent<AspectRatioFitter>();
}
GetComponent finds "thing" (such as a "light2D") which is attached to that same game object.
• You have some game object
• A script, Script.cs, is attached to that game object
• Some other thing (say, Light2D) is attached to that same game object
Inside the script Script.cs, you can find the other thing, using GetComponent.
Ideally, don't call GetComponent repeatedly, just call it once in Awake or whatever. (But you're a mile away from worrying about performance, so don't worry about it.)

using UnityEngine.Experimental.Rendering.Universal;
using UnityEngine;
public class Light2DController : MonoBehaviour {
void Awake() {
//assuming You have Light2D component in the same object that has this script
Light2D light = transform.GetComponent<Light2D>();
}
}
Unity 2019.3.0f1

Here's how you can access the Light2D(Script) components.
Unity Version: Unity 2020.1.4f1
Import using UnityEngine.Experimental.Rendering.Universal; into your Script.
Please find the below code example.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;//Important
public class Lighting : MonoBehaviour
{
Light2D theLights; // To Access the Light Components.
public float maxRange = 0.54f;
public float minRange = 0.31f;
public float flickerSpeed = 0.5f;
void Update()
{
//Assuming You have Light2D component in the same object that has this script.
theLights.intensity = Mathf.Lerp(minRange, maxRange, Mathf.PingPong(Time.time, flickerSpeed));
// The above Line is to create a flickering effect, You can also set a value like for example: theLights.intensity=0.5f, To set the intensity of the Light.
}
}
You can also access other Light2D components similar way
theLights.color = new Color(0, 255, 0);// here I am accessing color and setting a new color value.

In newer versions of unity (i'm using 2021.2.7f1) use this:
using UnityEngine.Rendering.Universal;
And then in code:
Light2D light = gameObject.GetComponent<Light2D>();

Related

Unity script doesn't "take" in editor

I am learning Unity. Working through the rollaball tutorial, I have come as far as video 8, where I add the line "public float speed=0;" this reveals what I already suspected, namely that in some way my script does not "take" in the unity editor.
I use Visual Studio code as my normal editor. I told Unity that it is going to be my editor for scripts.
In this tutorial, I started by pressing a "new script" button as recommended by the tutorial, and created the file PlayerControl.cs in the editor. However, as the screenshot shows, the editor doesn't look like it has really taken possession of edited script, and it certainly hasn't added "speed" as a visible field. Besides which, nothing that I try will actually move the ball.
Okay, so my Unity install is brand-new, and I can easily believe that I might have missed a bit. But where to look, how to diagnose? Is there a log file I should be looking at?
The meaning of the OnMove method is not entirely clear from documentation that I can find. Is it called when the mouse moves? If so, it too is being unresponsive.
Tutorial:
https://learn.unity.com/tutorial/moving-the-player?uv=2020.2&projectId=5f158f1bedbc2a0020e51f0d#
System: Mac OS 11.6
VS Code 1.74.2
Script code is below
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerControl : MonoBehaviour {
public float speed = 0;
private RigidBody rb; // so Inspector doesn't see it
private float movementX, movementY;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<RigidBody>();
}
void OnMove(InputValue mvt)
{
Vector2 movementVector = mvt.Get<Vector2>();
movementX = movementVector.x;
movementY = movementVector.y;
}
void FixedUpdate()
{
Vector3 movement = new Vector3(movementX, 0.0f, movementY);
rb.AddForce(movement * speed);
}
}
I don't know whether you have installed the visual studio code package or not. This is required to correctly integrate VS Code and Unity.
Just try saving the script again and return to Unity. Unity should now refresh and recompile the script into assembly then there will be the change reflected in editor.
And for the part where you can't understand OnMove() that explanation is as follows:
Since you are using Unity's New Input System, you would have created an action map. Unity will automatically call functions for each action in Action Map which is named [On + ActionName] OnMove() in all scripts. Since, the Behavior in PlayerInput Component is Set to Send Messages.

'Raycast' is not being recognized within C# Unity script

I'm following a Unity Augmented Reality Tutorial using ARFoundation (I've made sure the package has installed correctly, along with ARkit).
My code follows his to the letter, and yet Raycast does not appear to be recognized. I get this error when I hover over it:
'ARSessionOrigin' does not contain a definition for 'Raycast' and no accessible extension method 'Raycast' accepting a first argument of type 'ARSessionOrigin' could be found (are you missing a using directive or an assembly reference?)
I can't figure out what the issue is, and I've redone the tutorial twice now (the second time using Unity's 3D template instead of ARCore because it seemed that ARFoundation was locked when I used ARCore template.) I'd greatly appreciate if someone could take a look and let me know if they have an idea of how to resolve it.
Thinking it had to do with ARFoundation not installing correctly, I double checked and ensured that it was, and was updated to the latest version. I re-checked the code multiple times for errors, and I still cannot figure out why Raycast isn't being recognized. Below is the Unity script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.Experimental.XR;
using UnityEngine.XR.ARSubsystems;
public class TapToPlaceObject : MonoBehaviour
{
private ARSessionOrigin arOrigin;
private Pose placementPose;
private bool placementPoseIsValid = false;
// Start is called before the first frame update
void Start()
{
arOrigin = FindObjectOfType<ARSessionOrigin>();
}
// Update is called once per frame
void Update()
{
UpdatePlacementPose();
}
private void UpdatePlacementPose()
{
var screenCenter = Camera.current.ViewportToScreenPoint(new Vector3(0.5f, 0.5f));
var hits = new List<ARRaycastHit>();
arOrigin.Raycast(screenCenter, hits, TrackableType.Planes);
placementPoseIsValid = hits.Count > 0;
if (placementPoseIsValid)
{
placementPose = hits[0].pose;
}
}
}
Gotta google your problems, my dude.
From this post:
It seems that they have moved Raycast from ARSessionOrigin to ARRaycastManager in latest version. As mentioned in https://docs.unity3d.com/Packages/com.unity.xr.arfoundation#2.0/manual/index.html, you need to "add an ARRaycastManager to the same GameObject as the ARSessionOrigin".
Edit - you should also pay very close attention to the publication date for any tutorials. Some aspects of Unity have been stable for a very long time but some things break on a new year's release. UI Toolkit, AR, DOTS, etc. are all examples off the top of my head.

Camera Methods not found

Unity/C# dont find the method "Camera.ScreentoWorldSpace" or also "Camera.main".
i dont know why, i dont know if i just forget something, so please help.
I want to create a Raycast using the Mouse Position but when i wanted to use my main Camera to change the mouse Pos from screen Space to World Space it do not recognizes these Methods nor autocomplete it?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class Inspect_Button : MonoBehaviour
{
public string inspectName;
public Camera cam;
private GameObject markedLand;
private Vector3 mousePos;
// Start is called before the first frame update
void Start()
{
cam = Camera.FindObjectOfType<Camera>();
}
void OnEnable()
{
markedLand = GameObject.Find(inspectName);
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
mousePos = Input.mousePosition;
print(mousePos);
cam.ScreentoWorldSpace(mousePos);
}
}
}
It is likely an issue of Unity not generating your IDE's project file properly, leading to your IDE not detecting the Unity's API for auto-correct and such.
On your Unity Editor, Edit -> Preferences...
External Tools -> Ensure that the selected Editor is correct -> Regenerate Project Files -> Restart your IDE
Assuming you are using Visual-Studio and it still doesn't work, confirm there is Unity C# installed onto your Visual Studio, like so:
(Use Visual Studio Installer to check)
Solution for VS-Code instead.
Finally, Camera.ScreenToWorldSpace does not exists.You are probably looking for Camera.ScreenToWorldPoint.
Camera.main do exist though, and should work.

Can't add script component 'HealthDisplay' because the script class cannot be found

I have seen similar questions, but I legitimately can't understand my problem here.
I have created a new script called HealthDisplay, from within Unity itself. It generated with some sample code, and I tried to attach it to a UI object that's text - however that error shows up.
I looked up the error and got all sorts of suggestions, however the code was generated by Unity itself, and the name of the class matched the name of the file exactly. I added some more code and tried to attach it then, but it still didn't work. I also tried reinstalling both Unity and the Unity Hub, and still nothing. Here's the code within HealthDisplay.cs:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthDisplay : MonoBehaviour
{
private int health = 100;
public Text healthText;
// Update is called once per frame
void Update()
{
healthText.text = "HEALTH : " + health;
if(Input.GetKeyDown(KeyCode.Space))
{
health--;
}
}
}
The file, I've triple checked, is called HealthDisplay.cs. Its name matches exactly. Is there something I'm doing wrong, or could this just be some weird bug with Unity? Thanks.

Unity3D - get component

What is the simplest way to getcomponent in Unity3D C#?
My case:
GameObject gamemaster.
//C# script MainGameLogic.cs(attached to gamemaster).
A boolean backfacedisplayed(in MainGameLogic.cs).
A function BackfaceDisplay()(in MainGameLogic.cs).
Another C# script FlipMech.cs, which I need to check from MainGameLogic.cs if(backfacedisplayed == TRUE), I will call BackfaceDisplay()from MainGameLogic.cs. How can I do it in C#?
In js is rather straight forward. In FlipMech.js:
//declare gamemaster
var gamemaster:GameObject;
Then wherever I need:
if(gamemaster.GetComponent(MainGameLogic).backfacedisplayed==true)
{
gamemaster.GetComponent(MainGameLogic).BackfaceDisplay();
}
But it seems like C# is way more complicated that this.
in c#, you will get the component using this,
if(gamemaster.GetComponent<MainGameLogic>().backfacedisplayed==true)
{
gamemaster.GetComponent<MainGameLogic>().BackfaceDisplay();
}
Nick's answer didn't work for me when I countered this same problem. The script involved an Unity3d asset store that has its own namespace. When I put the class in the namespace, it started working.
using UnityEngine;
using System.Collections;
using Devdog.InventorySystem;
namespace Devdog.InventorySystem.Demo
{
public class changeStat : MonoBehaviour {
// ... rest of the code including the gameObject.GetComponent<>();
}
}

Categories

Resources