#💻┃code-beginner
1 messages · Page 88 of 1
why isnt my input going in here? Is it because its not a TMP If so how do I type it so it is? This is what the declaration looks like [SerializeField] public UnityEngine.UI.InputField inputField;
legacy InputField is not tmp inputfield
what is gui?
one line of code tells us nothing
yes just like you said, declaration is like
[SerializeField] private TMPro.TMP_InputField inputField;
or
using UnityEngine;
using TMPro;
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField] private TMP_InputField inputField;
}
Good morning, I keep coming up with a NullReferenceException when the game/app starts but I see nothing wrong.
Did this originally ping me? Discord alerted me to this as a message
https://paste.mod.gg/aphlawxayzhe/0 GameManagerScript
A tool for sharing your source code with the world!
which is attached to GameManager
Not sure what gives, I see nothing null.
32 goes to here: currentMoneyText.text = "$" + currentMoney.ToString("#,#");
which that line worked before...
make sure you don't have more than one of that component in the scene where any others do not have your text objects assigned
found it, script was attached somewhere else too, must of missclicked
Thanks 🙂
this is how it started (from a tutorial on YT)
and this is my changes / additions
need to fix scrollrect, it doesnt scroll right but bleh
So I had something really weird yesterday.
I added a version number to my API, making it not process any older versions of the game.
{
if (version == 2)
return true;
return false;
}
[CloudCodeFunction("SaveCharacter")]
public string SaveCharacter(int version, string playerId, int level, int experience, int strength, int dexterity, int intelligence, int statpoints, int basehealth)
{
// Only accepts saves from the latest version
if (!checkVersion(version))
return "Wrong game version.";```
But for some reason it just kept working on all the clients that did not have this version parameter yet?
Then I changed the 2 to a bigger number and then it suddenly started working (which means it stopped working for the older clients)
Any ideas? Just curious here
were you getting null pointer?
no errors or anything, it was just letting clients without version still save somehow
Yeah sorry - im on mobile and I guess i tapped your name at first
Personally I'd invert the final check, much easier to check directly for currentversion and blanket all the wrong versions in an else.
What channel should I join for ScrollRect help? Tried #🖱️┃input-system but its quiet atm.
it is a force update that request any client update the app?
do the checking on cloud is safer
Does a null bool return 0 or an error?
bool isnt nullable unless you specifically declare it to be so
I think it's some funky niche issue with partly undeclared bools being rendered as 0 then. But I'm probably very wrong.
uninitialized bool?
my vote is on the very wrong part, "undeclared" bools are just false. It is a struct and will have a value even if you dont assign it one. "Rendered" is just initialized
also they are definitely not directly converted to 0, i believe thats just a c/c++ feature
🤔
if it is c/cpp, it will be random value
just safety feature, initialize the memory to zero
What's the error?
So it will read the boolean struct as false if it's uninitialised?
it is the default value
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/default-values
that being said, you cant just do
void SomeMethod()
{
bool b;
if(b)
...
}
It doesnt really make sense to do anyways, but if the bool was global instead of local then it would work
https://dotnetfiddle.net/WWtZXY the global vs local thing if it wasnt clear
no errors, just very strange behaviour
Also let me know if you guys crack this, I'm very curious now
I dont think anyone here could suggest much about that problem, because theres definitely a lot more context we are missing in it. It could be something as simple as they forgot to change the version number. Or that the older versions of the game didnt have this code and would use the cloud function regardless. And then its possible they updated it in such a way where they tested a version where the client had this code
Just place the code in backend
If no version is provided or the version is less than supporting one, then dont process
The code I posted is on the backend in UGS Cloud Code Modules
It's called from clients - the issue was that my last client didn't have the version parameter yet, so it was calling the cloud function without that parameter, but the could function somehow still ran and saved the character
only thing I can think of is it somehow converted whatever the playerid string was to the number 2 - but I don't see how
UGS CCM seems kinda buggy though, so maybe it just didn't save or load properly
How do I add delay to a button click, let's say 0.5f seconds
so i need help to understand this code fully
so in my input manager both the horizontal and verticle is set to the x axis but the x axis shown in the scene is sideways. while i can understand the Input.GetAxis code i do not understand both theVector3.forward and Vector3.up code cos of the direction of the x axis and unity tutorial lack of explanation. Am i able to assume Vector3.forward code just means the direction the car is facing and the Vector3.up is sideways of the x axis.
sorry for the long paragraph im really confused at the axis
does anyone know how to fix this networking issue when i'm using netcode and i've created a server and joined on a different screen but it's not showing up the character but on the other screen i can see the character so one of the character is client?
oh i forgot the 4th code is set to trasnform.rotate my bad small mistake. though im still confused about the axis
A) Compare a variable to time
B) Use a coroutine.
i've been trying to figure this issue out for weeks but i can't seem to get both screen to see each other but only the other person can see and i can't see the character it's something to do with replicating the character
the weird thing is that the character has like two characters in the body which means the main player body is stuck to the other player but on my screen it looks perfectly fine but they can't see me but i can see them
try transform.forward instead of vector3.forward.
I believe transform is global, and transform is relative to the objects transform (Position/Rotation)
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Is your movement script client orientated?
using UnityEngine.UI;
using System.Collections;
using UnityEngine;
public class ButtonDelay2 : MonoBehaviour
{
public Button button;
public float delay = 0.5f; // adjust delay time here
void Start()
{
button.onClick.AddListener(OnClickDelayed);
}
void OnClickDelayed()
{
StartCoroutine(DelayClick());
}
IEnumerator DelayClick()
{
yield return new WaitForSeconds(delay);
}
}
debug log
This is my button delay script and it won't work
the movements are perfectly fine and they function normally it's just that the character's body is client on the other screen but i can see the body on the other screen which is odd
i attached it to the button and everything
Using Mirror or Netcode for Gameobjects?
How do you know it doesn't work? The coroutine does nothing but waits for the delay
You need to add some code after the yield
i'm using netcode for it
Which I'm new to coding
Whatever you want to happen, you need to add the code for it after yield return new WaitForSeconds(delay);
So that it waits and then runs the code
You didn't tell us what you want the button to do
do i change the vector3.up to transform.up as well
So like a Onclick?
I want it to be able to be pressed once every 2 seconds or so
Can do, depends on the context of it
Okay so you want to disable it, then delay, then enable it
What's your process for sending something to the server / being updated to cleints
can you show an example
yeah
is it okay if i could dm? it's kinda hard to explain
disable it after click tho
@craggy bane Set button.interactable to false before the yield... line, then set it to true after
That is, if you want it to show but be disabled
Yeah go for it
Yes
Thanks
ah i see ... though i still have confusions with the axis, the x axis is pointing sideways yet my vertical imput is set to x axis. then when i code it in transform.forward shoudnt it travel along x axis instead?
is it possible to change the size and stuff of my players collider in code
Yes, look at the documentation for that collider and see what's available
ah lol; i saw the beginner scripting in the pinned comments how come i dont see beginner scripting in unity pathways haha
Use the Z axis instead ( or you can rotate the model so it is facing blue arrow forward.transform.right).
Hold on I think I'm conflating X and Z
using UnityEngine.UI;
using System.Collections;
using UnityEngine;
public class ButtonDelay2 : MonoBehaviour
{
public Button button;
public float delay = 0.5f; // adjust delay time here
void Start()
{
button.onClick.AddListener(OnClickDelayed);
}
void OnClickDelayed()
{
StartCoroutine(DelayClick());
}
void OnEnable()
{
button.onClick.AddListener(() => button.interactable = false);
}
IEnumerator DelayClick()
{
yield return new WaitForSeconds(delay);
}
void OnEnable()
{
button.onClick.AddListener(() => button.interactable = true);
}
}
the disable works
but enable after the delay doesn't
Type 'ButtonDelay2' already defines a member called 'OnEnable' with the same parameter types
Oh wait nvm I fixed it
That's not what I told you to do
What
IEnumerator DelayClick()
{
button.interactable = false;
yield return new WaitForSeconds(delay);
button.interactable = true;
}```
This is all you needed to add
Are you using ChatGPT? Where did this OnEnable/OnDisable stuff come from?
My script uses events
theres no z option in input manager
This doesn't work gang
Don't need it there, just map Z to vertical or horizontal if it's moving sizeways / red arrow forward
Ok I got it thanks
replace X with Z, or rotate the model inside of an empty parent object
I am trying to make a parallax effect in my game, i want the background to be generated again once it has moved off the screen.
My background has lots of objects, how can i attach all of this into a sprite renderer?
lol the program works just fine haha ... maybe i just need more time to understand the axis thanks for the help anyways @queen adder
Can anyone help with this?
Yo osmal how do I apply this script to 4 other buttons
It's only working on one right now
Add the script component to the other objects too?
It won't work
Things work when you do it correctly
And if you use this code ^ then it's on you
So what code are you using?
Urs
And what doesn't work exactly?
using UnityEngine.UI;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class ButtonDelay3 : MonoBehaviour
{
public Button button;
public Button button2;
public Button button3;
public Button button4;
public float delay = 0.5f;
public UnityEvent enableButton;
void Start()
{
button.onClick.AddListener(OnClickDelayed);
button2.onClick.AddListener(OnClickDelayed);
button3.onClick.AddListener(OnClickDelayed);
button4.onClick.AddListener(OnClickDelayed);
}
void OnClickDelayed()
{
StartCoroutine(DelayClick());
}
IEnumerator DelayClick()
{
button.interactable = false;
yield return new WaitForSeconds(delay);
button.interactable = true;
}
IEnumerator DelayClick2()
{
button2.interactable = false;
yield return new WaitForSeconds(delay);
button2.interactable = true;
}
IEnumerator DelayClick3()
{
button3.interactable = false;
yield return new WaitForSeconds(delay);
button3.interactable = true;
}
IEnumerator DelayClick4()
{
button4.interactable = false;
yield return new WaitForSeconds(delay);
button4.interactable = true;
}
}
I did this
now
Let me test this
Remove those 2-4, go back to what you had
Then add the script to the buttons, not some other object
Thats what I did
Okay well you don't need 4 methods/button references
Each button takes care of itself
this one doesn't work either
I suggest looking into for statements, indexing and lists next
You can turn scripts like that into modular lists where adding objects is as easy as pressing a little tick and dragging it in instead of making a unique variable for every object.
Hey yall i got a question.
In my current project i have a level select screen.
I opted to make it a scroll view so the player just has to scroll up to see new levels or down to see previous levels. (Something like the candy crush level layout).
My only issue is. Im trying to save the level that the player is currently on.
Eg. If they on level 50 and they exit the game and go back into the game i want the level to show as level 50. I dont want it starting at level 1 again and then they have to scroll all the way back up to level 50.
So does anyone know how i would be able to save the position of the current level the player is on?
My levels are not prefabs. They are images that have a button script on them. And i setup my level layout (type of board, goals, etc) in a scriptable object
Sorry for the bad explanation. Im not sure how to ask this question.
Im using unity and c#
Basically i have say 100 levels.
Player is on level 50.
Player changes scenes or exits game then returns back to level select screen.
I want the current level of 50 to be shown in the centre of the screen instead of level 1. So that way the player doesnt have to scroll for 10min to find their current active level
PlayerPrefs should help
save the position to that then get and set the position in the start function
The position of the active level thats inside the scroll view?
So would that then make my scroll view auto jump to the current level the player is on?
I'm not sure what physically changes inside of the scroll view as I don't use it, but I think it adjusts the position of it's child object right
Also how to i save a position in playerprefs? 😅
https://docs.unity3d.com/ScriptReference/PlayerPrefs.html
they're incredibly useful
Why cant i drag a prefab onto a sprite renderer?
Im not too sure.
I know i can make a layout group but then my content will all be in a straight line which i dont want.
I want it in a squiggly line so i have been duplicating the first level image then placing them in the positions that i want them in
Hi, everyone. Trying to make an enemy to shoot. Was just testing. Does anyone know why unity stopped entering the play mode after this lines of code?
while(true)
{
randomAttack = Random.value;
if (randomAttack > attackProbability)
{
enemyAnim.SetTrigger("EnemyAttackTrigg");
new WaitForSeconds(1);
}
}
might help too
Thank you
Why cant i drag a prefab onto a sprite renderer?
you have a while loop without an exit condition (that never ends), so the program crashes . . .
also, try formatting the !code when/if posting . . .
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Tis a prefab, and not a sprite
How can i make it so my script is using a prefab
does the prefab have a SpriteRenderer component on it?
I am making an endless runner, i want the background to be infinite (so it keeps generating new parts)
my background has lots of different objects tho
[SerializeField] GameObject spritePrefab;
There's probably better ways of doing it than instanciating a prefab tbh
How would this work?
a prefab is just a GameObject saved as an asset in your project folder. make sure the object you drag has the correct component (type) as the field in the class (script) you want to attach it it . . .
My code rn is :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallex : MonoBehaviour {
private float length, startPos;
public GameObject cam;
public float parallexEffect;
void Start () {
startPos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate () {
float temp = (cam.transform.position.x * (1-parallexEffect));
float dist = (cam.transform.position.x*parallexEffect);
transform.position = new Vector3(startPos + dist, transform.position.y, transform.position.z);
if (temp > startPos + length) startPos += length;
else if (temp < startPos - length) startPos -= length;
}
}
maybe a seamless teleport?
yes it is
thats what i wanna make
but my background has lots of objects in, instead of being one sprite
like this
i have them saved as prefabs tho
Yeah I'd suggest a seamless teleport to the start or spawning a 2nd copy of the prefab with Instanciate
then group them into a prefab and use that prefab so everything moves together . . .
and attach the prefab to the script?
or use multiple parallax scripts for each layer to move them independently from others. that works if each layer moves at different speeds . . .
i have that already
p. p. parallax
i always had a rough time making parallax scrolling stuff to be perfect
A quick tutorial on how to achieve a cool parallax effect with infinite scrolling. This method uses a simple script, which means you don't need to mess with the z-axis. Personally, I think this is much better for a 2D game, and couldn't find any easy tutorials on it, so figured I would make my own. Go to my discord to download the tutorial resou...
But he is using assets not prefabs
and idk how to transform the prefab
what
i will try
does that mean i need to change in the hierarchy, that the layers are prefabs not lots of objects?
I'm not sure I'm getting what you're asking
can it be like this
or does it have to be prefabs
you want the layers to come in on say the 2nd loop layer 2?
no they start from the beginning
I have no idea what you mean
nevermind
Show code
Rotation is a quaternion, a four dimensional normalized vector. The x, y, and z values of which have nothing to do with the x, y, and z values of normal euclidian space.
You can get a vector3 representing that orientation with .eulerAngles instead of rotation, but there's an infinite number of vector3s that can represent that quaternion, so it might not match the inspector exactly, but it will at least be a number with three values that are in degrees
What do i need to replace transform.position = new Vector3(startPos + dist, transform.position.y, transform.position.z); with to make it transform the prefab instead?
you'd need to initialize a variable of the prefab, then change them to target that yummy variable
how would i do this?
yes
This will move the object this script is on. Is this script on the prefab
what Gameobject specifically is it on
Show the full script. !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parallex : MonoBehaviour {
private float length, startPos;
public GameObject cam;
public float parallexEffect;
void Start () {
startPos = transform.position.x;
length = GetComponent<SpriteRenderer>().bounds.size.x;
}
void FixedUpdate () {
float temp = (cam.transform.position.x * (1-parallexEffect));
float dist = (cam.transform.position.x*parallexEffect);
transform.position = new Vector3(startPos + dist, transform.position.y, transform.position.z);
if (temp > startPos + length) startPos += length;
else if (temp < startPos - length) startPos -= length;
}
}
Did you assign cam?
Any errors in console?
No errors
You sure? Show the console window
While the game is playing?
Show the inspector of the objects
You said they weren't moving
I mean, when the game is running, the objects move slowly (trees, rocks etc)
But when i get to the end of the background, nothing happens
It needs to move the old section of the background and move it to the front
this happens
Why would you expect it to do that if you didn't write code for that
i thought i did
float temp = (cam.transform.position.x * (1-parallexEffect));
if (temp > startPos + length) startPos += length;
else if (temp < startPos - length) startPos -= length;```
Doesn't this do that?
@wintry quarry
Have you tried logging those values and see if it ever fulfills that condition?
Idk, did you test if that code is running when you expect it to?
ill try
when it reaches 50 it should move the background
startpos + length is always -1.38
for all objects
startpos doesnt change for some reason
You need to log all the variables.
temp
length
startPos
Why would it?
You don't change it anywhere other than inside these conditions
And if you're depending on it changing to enter these conditions that's not going to help much
Length is always 0. StartPos is always -1.38. Temp is changing to where the player is
When temp is 50, the first background should be moved
What do i need to change to make this work?
Where does 50 come into all this? I don't see any 50s anywhere in the code
each background has a different point when it needs to be moved
else if (temp < startPos - length) startPos -= length;```
I thought this did it ?
Okay but where did you get 50 from?
You said start pos and length are constant values
its just when the first object needs moving
Ohh ok
So I actually got it working, thanks
yes its -1.38
Okay, and what a out -1.38 - 0?
the same..
So how were you expecting that math to change the value of startPos
length needs to be changed?
its the size of the gameobject?
idk
i just followed this
A quick tutorial on how to achieve a cool parallax effect with infinite scrolling. This method uses a simple script, which means you don't need to mess with the z-axis. Personally, I think this is much better for a 2D game, and couldn't find any easy tutorials on it, so figured I would make my own. Go to my discord to download the tutorial resou...
Where do you set length
So then the size of this objects sprite is 0
but surely if temp is > than startpos+length, then startpos would change?
It would. You'd add or subtract length to it
Which is 0
And again, what is -1.38 + 0?
Make length not 0
so make the camera start not at x=0?
What does that have to do with length
length = GetComponent<SpriteRenderer>().bounds.size.x;
oh
he sets the size to 5
i didnt realise
And how did you get "camera position" out of that line? What about that line made you think the length had anything to do with camera position
You should read the code you write
but my camera size
is also 5
yes
then where can i change this value in the inspector?
Again, where are you getting camera from this
bounds.size?
Why do you keep going back to the camera
What about this line makes you think it has anything to do with the camera
So then why do you keep coming back to the camera to figure out why this line is 0
Code means things. It's not magic. The code only does exactly what you tell it to. So, what does this line set length to?
So, what is the size of the sprite in this objects sprite renderer
When you click on the sprite file in unity it should show you the size of it
What sprite does this object use
Just pick one of your objects with this script. What sprite does it have
Because it's the size of the sprite file.
It's how big your image is
ohh
So that's why length is 0
right
Because the width of this object is 0
Either give it a sprite or don't set length to be the width of the sprite
I am spawning one object and i have 5 scripts with different movement pattern.
i want this object to adapt 1 script movement depending upon some bool or int value or scene.
do i have to make it's prefeb 5 time and attach each script or is there a better way to do it?
You can make a unique* prefab for each script if you wish, but otherwise that's fine too
transform.forward
lol
Wdym by "from a local rotation"?
And what is "a transform.forward"
If you can't explain, we can't answer 🤷♂️
transform.forward is in world space
if you need the forward in local space, multiply the rotation with vec3.forward
use ms paint drawings or gif recordings of strange behaviour if you're struggling to explain
The object's forward direction in its local space is always just Vector3.forward
The object's forward in world space is transform.forward
i thought vector3 forward was just the none relative forward direction
Vector3.forward is world relative
[Transform].forward is object relative
Vector3.forward has no inherent dimensional meaning until it's used in context. It's just the vector (0, 0, 1)
I'm looking for a ball that moves just like pong in a 3d world but only in the X and Z direction.
Until this point, I did not manage or found to have any good scripts that does just that. I'm getting desperate : / Even chatgpt doesnt know
Right, but "Local forward direction in local space" is just 0, 0, 1
ahh, un-confused
transform.forward is in world space. It is a vector that takes the rotation of an object into consideration when making the vector though. Think of it like a conversion
It is the world space forward of an object
var targetDir = (target.transform.position - rb.position).normalized;
Vector3 forwardDir = rb.rotation * Vector3.forward;
var currentAngleX = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.right);
var targetAngleX = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.right);
var currentAngleY = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.up);
var targetAngleY = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.up);
var currentAngleZ = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.up);
var targetAngleZ = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.up);
float inputX = controller.UpdateAngle(Time.fixedDeltaTime, currentAngleX, targetAngleX);
float inputY = controller.UpdateAngle(Time.fixedDeltaTime, currentAngleY, targetAngleY);
float inputZ = controller.UpdateAngle(Time.fixedDeltaTime, currentAngleZ, targetAngleZ);
Debug.Log($"{currentAngleX} {targetAngleX}");
rb.AddTorque(new Vector3(inputX * forceAmount * 0, inputX * forceAmount, inputX * forceAmount*0));
curently having problems with angles
if anyone know how to fix it
This is massively overcomplicated 😬
I'm not sure what controller.UpdateAngle does
Something like this is what I'd do:
Vector3 dir = target.transform.position - rb.position;
// Optional, if you want to rotate only on the y axis:
dir = Vector3.ProjectOnPlane(dir, Vector3.up);
Quaternion target = Quaternion.LookRotation(dir);
Quaternion current = rb.rotation;
Quaternion diff = target * Quaternion.Inverse(current);
Vector3 eulers = diff.eulerAngles;
// plug eulers into your PID controller here if you want
// add the torque
rb.AddTorque(forceAmount * eulers);```
not sure how to integrate it into your pid controller
maybe just using eulers
Probably would be cleaner if it worked directly with quaternions though
i need a current angle(gameobject angle)
and target angle
and it does pid stuff to turn it
i need it for realistic missles
what type of missile you modelling
realistic, i dont want want it to look arcadey so i would use pid controller so it can also be doged(as like missle having trouble to keep up)
dont worry about pid controller, giving input to pid controller is a problem here
IR air to air style?
ye
that's a lot of vector math
var currentAngleX = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.right);
var targetAngleX = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.right);
var currentAngleY = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.up);
var targetAngleY = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.up);
var currentAngleZ = Vector3.SignedAngle(Vector3.forward, forwardDir, Vector3.up);
var targetAngleZ = Vector3.SignedAngle(Vector3.forward, targetDir, Vector3.up);
this is the main problem
the SignedAngle's
Does anyone know why my text isn’t appearing? I tried adjusting the font size but it isn’t apearing
Are you sure TextMeshPro is downloaded? I had the same problem and I removed, then added the component again and it automatically opened an install prompt.
are you looking at it from the right direction?
Also #📲┃ui-ux
Yes I am, any direction will not work, also when I start the game it doesnt appear
yes it works for other texts
only this specific one it doesnt
Could be the scale of a parent object that's messing with it as well. But yeah probably not coding related.
is this a world space canvas or something else
Any solution to find the right scale?
turn off autosize and try playing with the size
yes it is
you should generally not be scaling UI at all
Didn’t work
The scale of every canvas element should be 1,1,1
alright, but its absolutely massive then
Change the size parameters instead (width/height)
Your current scale is bigger than 1,1,1
Which is what I'm talking about
This should also be 1,1,1 then you can change the size
Change width and height. Not scale.
Scale should be 1,1,1
so if i have 4 points defining 2 segments, (x1, y1) to (x2, y2), and (x3, y3) to (x4, y4)
how would i write code that calculates if those two segments intersect each other?
(thats for a linerenderer script btw)
I did all of that for every object, still not showing up
Every UI in my canvas
Oh I figured it out
It was the Z scale being 0 for some reason, thanks for the help!
Maybe a good chatgpt question for once. It gave a pretty good solution involving cross products when I asked.
looks like an issue with visual scripting
I have a question, can I have 2 different post processing volumes that affect different objects? Or different cameras?
Yes i know everyone seees it
I have searched for a way to do this on google and youtube and it seems that no one knows how to do this, or it doesn’t work
Probably a question for #💥┃post-processing
I think they bring it up because this is a code channel. #763499475641172029 has a completely separate server. Very few people on this channel know much about visual scripting
Hello! for some reason when I run my game in the editor, the audio mixers seems to be global, but when I build the game the mixer volumes seems to reset on every scene, this is how I am writing the mixer volume. In the editor I can verify the volume stays consistent in every scene but in my builds the volume resets to 0 every time on every scene, also I can verify both Debug.Log's get called in development builds (volume doesnt stay consistent still)
public class SettingsUI : MonoBehaviour
{
public AudioMixer audioMixer;
public Slider effectsVolumeSlider;
public void Start()
{
if (PlayerPrefs.HasKey("effectsVol"))
effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
else
{
PlayerPrefs.SetFloat("effectsVol", 1);
effectsVolumeSlider.value = PlayerPrefs.GetFloat("effectsVol");
}
}
public void SetVolume(float volume)
{
float debugVol;
Debug.Log("Setting volume to " + volume);
audioMixer.SetFloat("effectsVol", volume);
PlayerPrefs.SetFloat("effectsVol", volume);
audioMixer.GetFloat("effectsVol", out debugVol);
Debug.Log("effectsVol Float Value: " + debugVol);
}
public void GoBack()
{
SceneManager.LoadScene("MainMenu");
}
}
yo how do i add a timer on my quest script
I have been advised to use Vector.Normalize by a friend, but I still do not understand how it works
Isnt a Vector value a single point? how can it have direction or lenght?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
hi i have maybe a dumb question but can i take every single composent of this picture with unity if yes how?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QuestGiver : MonoBehaviour
{
public Quest quest;
public Player player;
public float timerDuration;
public GameObject questWindow;
public Text titleText;
public Text descriptionText;
public Text RepText;
public Text OctoSnackText;
public Text TimerText;
public void OpenQuestWindow()
{
questWindow.SetActive(true);
titleText.text = quest.title;
descriptionText.text = quest.description;
RepText.text = quest.RepReward.ToString();
OctoSnackText.text = quest.OctoSnackReward.ToString();
TimerText.text = quest.Timer.ToString();
}
public void AcceptQuest()
{
questWindow.SetActive(false);
quest.isActive = true;
player.quest = quest;
}
public void DeclineQuest()
{
questWindow.SetActive(false);
quest.isActive = true;
}
public void OnTimerFinish()
{
StartCoroutine(TimerRoutine());
}
IEnumerator TimerRoutine()
{
yield return new WaitForSeconds(timerDuration);
quest.OnTimerFinish();
Debug.Log("Timer Finished");
}
}
quest.OnTimerFinish();
'Quest' does not contain a definition for 'OnTimerFinish' and no accessible extension method 'OnTimerFinish' accepting a first argument of type 'Quest' could be found (are you missing a using directive or an assembly reference?)
How do I fix this issue
not a code question
I'm trying to make a timer on a quest script
where i need to ask so?
#📲┃ui-ux probably
Then my guess would be that Quest does not contain a definition for OnTimerFinish
yes
😭
Why are you crying
I have a meeting with the company who created The Line
NEOM
how could you be using something that dont exist
So why are you trying to call a function that you didn't make
I had no sleep for the past 13 hours
I'm sorry cuh
i just fixed it
thanks
dawg now its saying The type 'QuestGiver' already contains a definition for 'OnTimerFinish'
Probably a duplicate script
Or two functions in one class
Are you confusing Quest and QuestGiver?
No
A Vector3 is 3 floats. So for example transform.forward is 0, 0, 1.
So its a vector3 of length 1, that points forward. You can also have 0, 0, 500 of course.
That's a vector3 of length 500 that also points forward.
Lets say you move left and forward, so you press A and W, and force that into a vector, which is -1, 0, 1.
You want to normalize this, because you don't want the vector to be longer then 1, then you get ~-0.71, 0, 0.71. This is also the reason why old games move faster diagonally, because they don't normalize the input vector.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Quest
{
public bool isActive;
public string title;
public string description;
public int RepReward;
public int OctoSnackReward;
public int Timer;
}
this is the quest script
So where's the function
ontimerfinish?
yes
So actually yes you are confusing them. Notice how this doesn't have the function
it goes here as int or what
Do you know what a function is
Or "Method" I guess if you wanna be technical
That was a comment towards anyone else who felt like correcting my terminology
Ok
Because technically C# doesn't have functions, it has methods
I thought you said you fixed it
i fixed it then it gave me this
(51,9): error CS0102: The type 'QuestGiver' already contains a definition for 'OnTimerFinish'
So where's the function
dawg idk
its been 6 minutes just explain to me like im a baby learning his alphabet
Okay: If you want to call a function, it has to exist
Where do you want it and what do you want it to do
I want it to count from 139 to 0 and want it in my quest giver
If you want it in the quest giver why are you calling it on the quest
oh, okay! thanks!
so it will normalize the vector based on 000
hm, is it possible to normalize the vector relative to another vector?
because one of u told me to
when
Quest giver has that method, not quest.
Gangy
You are the one who is trying to call the function on Quest
If you want to do that, it has to exist
So, why are you trying to call Quest's function if you wanted it to be on the quest giver
do I need to make like a seperate quest script with the name quest time
If you want to call a function
so it will normalize the vector based on 000
It makes a vector of length 1, so not sure if that's what you tried to say.
What're you trying to do on that line?
have a good day bro
You're calling a function OnTimerFinish on the Quest object. Quest does not have a function OnTimerFinish
Yes cuz someone told me to gang
So, instead of trying to call a function that doesn't exist
forget that
And I'm not sure what you mean by Normalizing a vector relative to another vector, that doesn't make much sense to me.
so just call it on questgiver
Either
A) make it exist
or
B) don't call it
sorry, lemme try to explain better-
Perhaps if you explain your problem that your friend told you why you need to use Normalize would make it all a bit more sense.
Right so
I want to create a random point in a circular area. My friend told me to find the center of that circular area, modify it by a random vector, and then normalize the resulting vector, and then multiply that by a random value between 0.1 (a small number ) and the radius of that circle
something like this
ab is the centre of the circle, x, y is the random point created by the first modification
https://docs.unity3d.com/ScriptReference/Random.html
You could just use the existing methods for a random point:
insideUnitCircle Returns a random point inside or on a circle with radius 1.0 (Read Only). So this is 2D
insideUnitSphere Returns a random point inside or on a sphere with radius 1.0 (Read Only). And this is 3D
oh
thank you!
Debug.Log("Welcome to the");
And sure you could do what your friend told you.
Just have an random x value, random y value between -1 and 1, make a vector 2 out of it, normalize it and multiply that vector with a random value.
Then add your original a, b to that.
Okay, that helps me a lot- could I just
then create the random point, then add a, b to it?
If I read your question correctly, you can do insideUnitCircle and multiply it by how big of a cirle you want + your a, b vector.
That should do the trick.
yep, thats it, thanks
can you find the vector2 values of a transform.position value?
I can be implicitly converted, so you can just do Vector2 = Vector3
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
hi lads, i have something weird going on, i have a physics.raycast that hits a big collider, but it returns the collider on its parent game object, even though im shooting at the smaller collider, any way i can fix this?
here ive sent the hirearchy of the gameobjects, their colliders, my code and the debug resaults
i know it looks overwhelming but its not a lot trust me
in short : raycast hits object B, returns object A. object B is a collider that is a child of object A
use hit.collider.gameObject, not hit.transform.gameObject
whats the diffrance?
hit.transform and hit.rigidbody refer to the object that has the rigidbody
ohhhhh
why would transform give me the rigidbody?
that seems weird
A rigidbody sort of "claims" all colliders on it or child objects. This allows a rigidbody to have complex shapes without needing a high fidelity mesh collider, and gives you a way to differentiate parts of the object
It doesn't give you a rigidbody, just the transform of thet object that has it
If an object has a rigidbody, it becomes responsible for handling raycasts and other physics queries
for example, if you have a headshot hitbox, you still want the player's rigidbody to be the one that reports the hit, so you can call a function on that player
https://gdl.space/rijopuqahi.cs Can anyone help me, I am trying to load different backgrounds based off of the scene my character was previously in, I've tested and the SceneIndex is getting passed correctly through my scriptable object. My issue is when the battle starts the background is all white, i'm guessing it cannot find the refence image.
I have tried the full file path but thats not working
Your code is using Resources but you haven't shown your Resources folder, what does that look like?
what is the other method? beside making unique prefeb?
Thats probably my issue then, its not in the resources folder.
This is a series of articles that provides an in-depth discussion of Assets and resource management in the Unity engine. It seeks to provide expert developers with deep, source-level knowledge of Unity's Asset and serialization systems. PLEASE NOTE: this tutorial has now been deprecated. We now recommend using Addressables for your projects and ...
So i have them in there now,
i have a tetris game but when a piece is at the bottom it can still move side to side
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this is board
did you debug when you call HandleMoveInputs
no?
Looks like you enable input at any time that Time.time is greater than moveTime
and moveTime is only ever changed if valid is true
So see if that's being read as true when you don't expect
so what do i change
huh
you have to learn to debug if you want to get anywhere with code
ty
https://pastebin.com/GNFPqzAP
It doesn't register collisions and idk why. I have a spike set to trigger and a triggerbox around my character. At the beginning of the scene (When I start it) it registers the first debug log, but never again. Neither when colliding with smth that is a trigger or wehn colliding with smth. that isn't.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Hello, Im trying to save my game with binnary. I followed a tutorial about it and i tried to not change anything.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class DersData
{
public bool[] dersDurumu;
public DersData()
{
dersDurumu = new bool[10];
}
}
public static class SaveSystem
{
public static void Save(DersData ders)
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream fs = new FileStream(GetPath(), FileMode.Create);
formatter.Serialize(fs, ders);
fs.Close();
}
public static DersData Load()
{
if (File.Exists(GetPath()))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(GetPath(), FileMode.Open);
DersData data = formatter.Deserialize(stream) as DersData;
stream.Close();
return data;
}
else
{
Debug.LogError("Save file not found in" + GetPath());
return null;
}
}
private static string GetPath()
{
return Application.persistentDataPath + "/dersData.qnd";
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DerslerScript : MonoBehaviour
{
[SerializeField] List<Button> dersler;
public DersData data;
private void Awake()
{
data = SaveSystem.Load();
print(data);
}
public void YaptiYapmadi(int index)
{
if (dersler[index].image.color == Color.red)
{
dersler[index].image.color = Color.green;
data.dersDurumu[index] = true;
}
else
{
dersler[index].image.color = Color.red;
data.dersDurumu[index] = false;
}
}
}
When I save the game there is no problem. But when I try to load i get this error:
SerializationException: End of Stream encountered before parsing was completed.
You should not use it at all
What tutorial did you watch? From like 1995 ?
No like 2021
I'll build to android
I tried to watch a tutorial for PC too but I don't know if it's can be used to android. so i just found a new tutorial.
hey guys, any tips on how to do that movement with my enemy? like passing by the player next to it, and going outside the view, and coming back other sice, almost in a straight line? not in a circle.
Idk if it's going to work on Android, I'd try playin with System.IO.File.WriteAllText()
Thanks I'll try it.
I've never done it, but if a circle doesn't work, an elyptical orbit might?
maybe, i am just trying to figure it how, tried some stuff and didnt work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Die2Piks : MonoBehaviour
{
// Start is called before the first frame update
public GameObject Player;
public Vector3 Startposition;
// Update is called once per frame
private movement Moving;
void Awake(){
Moving = GetComponentInParent<movement>();
}
private void OnTriggerEnter(Collider other)
{
Debug.Log("Ded Trigger 1");
if (other.gameObject.CompareTag("Death"))
{
Debug.Log("Ded Trigger 2");
Moving.enabled = false;
Debug.Log("Ded Trigger 3");
Player.transform.position = Startposition;
Debug.Log("Ded Trigger 4");
StartCoroutine(enable());
}
}
IEnumerator enable()
{
yield return new WaitForSeconds(1);
Debug.Log("Ded Trigger 5");
Moving.enabled = true;
}
}```
easier to read if you can help
Which logs do you get
is there a YouTube tutorial that explains or teaches working with lights and glow for absolute beginners? or a document?
Glow is usually a post processing effect called 'bloom'
Light flares exist also
from the ones i give out? the first once, when the scene starts and then none. Is there another place to get logs?
Sounds like it's rotating along an oval-shaped pattern . . .
If the first one logs and none of the others, then this object collided with an object, but that object doesn't have the tag Death
kind fo yes, but woiuld be more like a straigh line.. just passing by it.
It doesn't log on collision. It logs once at the very start of the scene, then never again
If the thing that logs is your Ded Trigger 1 then it is colliding with something, or the function wouldn't be running
Is this script on the player, and what does the hierarchy look like?
I know that, that is what is confusing me. The player starts a bit in the air to avoid clipping, it lands on the ground, which isn't a trigger, the player itself has multiple objects, but only the one with the script is a trigger. It collides once with a trigger, idk which, and then never again.
@verbal dome the script is on Capsule, which is a trigger
Does player have a rigidbody?
no, only a player controller
How about instead of logging random text that doesn't give you any information, instead log the object you collided with
Wait a sec
it logs the character controller
Then whatever object this script is on is colliding with the character controller
it is, i know that because the character controller is inside it. Just why doesn't it react to anything else and since when is a character controller considered a trigger? I've never heard of that before.
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
Debug.Log($"{name} was triggered by {other.name}", this);```
- I have a 3D Collider on the capsule and on the spike
- isTrigger is on on both
3.is where my error was. thx, good to know
Rigidbody doesn't mix with CharacterController btw.
i know, it on the spike. I've already made painful expiriences...
does the rigidbody rule also apply to OnCollisionEnter?
Yep
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 3D Rigidbody on at least one of them
Commandments are eternal
thx
its giving me null
did you plug output in the inspector
If not You have a copy somewhere
either output doesn't have a textmeshpro on it
you 're probably looking for a TMP_Text, You have to show more context
yeah i see it now thx
someone know how to fix this?
Show !code for ReadInput
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
public class ReadInput : MonoBehaviour
{
public string input;
public Button gameb;
public void Readstringinput(string s)
{
input = s;
Debug.Log(input);
}
}
Did you save
yup
Run it again
ok
so its not giving me a error but its not showing the text I put in the input field
Nothing in this script does anything with the string you pass it
ohh ok\
what about the Log?
hello i used a code from chatgpt and theres an error that says "the type namespace "IEnumerator" caannot be found"
ive never heard of a IEnumerator what is that
🙄
show code
put in code block please 🙂
😅 k
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i feel like your disapointed that i used chatgpt..
yes because it probably didn't mention about namespaces
chatgpt sucks at coding
its spam generator
yup
i just wanted to see what it does
even when you ask it to explain what parts of code do, it can still get it wrong
yup just spews other peoples words scrambled with no verification of accuracy
once you learn the very few basics you can pretty much solve anything
alright scrap chatgpt
you can make it work if you want to quickly solve some very small beginner queries, but anything more is impossible for chatgpt
In Unity context they are used for coroutine but they are more than that
just goes iterates through a collection
but unity did some black magic and made it some async thing
the code i did yesterday i believe it work its the "inspector bar" thats wrong but i dont get what
question: is starting a coroutine within a coroutine a good idea?
yea why not
depends how many you're calling and where, everything you do has impacts
but its pretty normal to StartCoroutine from another coroutine
yeah one of my teachers advised me to be careful about how many updates i use and how to be more efficient
Github Copilot >
Very useful, if you are a student in highschool I highly reccomend it. (Dont use it as a tool, use it as a friend to ask questions and learn 🙂 )
this isn't even the same tech
🤷♂️ depends on the use case. Id say it'd be more indicative of a weird coding practice but could have valid scenarios
actually heard that's pretty good but its also paid so i passed on it
If you are a student, you can keep it for free until you leave highschool.
Alongside with a shit ton of other benefits
im in uni but i dont think our campus has copilot as a free thing
hell they barely even have adobe
Doesn't matter if your campus does it or not
you can probably get it still thru Github
Github regardless of if campus agrees allows you to signup
Just need some form of POE (proof of education)
like student id works
oh interesting
(best thing is student id)
abuse it while you can
others are hard to get in with
rq
is this code ok https://hastebin.com/share/nubivamine.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
it felt kind of cheaty though
i think it is
using chatgpt
It is cheaty using ai, that's why I use it as a friend not a tool. Don't get addicted to it, learn off of it.
it does feel like cheating
ok in what sense, does it work?
does it compile? probably
fuck around and find out
just like cheating you won't learn anything
then you have to fake it to make it your whole life
yeah originally i was using it to generate me a script and explain every part of that script until I understood what was going on and why. But eventually it wasn't explaining things properly and was getting stuff wrong so i stopped using it
i never want to cheat my way through with chatgpt because its so short sighted, learning it yourself is much more fulfilling
thats why you limit yourself and dont ask it straightforward questions
for some reason i cant get this oncollisionenter to work
can someone help troubleshoot
i mean collision exit
case closed
it doesnt work still
bro no its a collision exit and it doesnt work. when my object leaves the other collider its doesnt reload the scene
Place a log in that, does it execute?
It's weird how the method name is a bit grayed out, but maybe it's just the analyzer reporting incorrectly
Check in 3d view that they are actually going to touch? Does that matter? I don't know
The Three Commandments of OnCollisionExit2D:
- Thou Shalt have a 2D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt have a 2D Rigidbody on at least one of them
yeah it says "unused method"
object1 has polygon collider
object 2 has a collider and a rigibody
dont see whats wrong tbh
Show the full !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
im trying to make a coroutine where an object moves to the positions of game objects inside a list until it reaches the end. This is what I have so far but im not sure if im on the right track. The way I think this is working is that for every object inside hitList a coroutine is being started in which the object will move to that position and once it has reached close enough to that position, a boolean will be returned which tells the previous coroutine to do the same for the next object. Is this correct or am I wrong?
{
for (int i = 0; i < hitList.Count; i++)
{
cr = StartCoroutine(MoveToEnemyPositions(i));
yield return cr;
}
}
IEnumerator MoveToEnemyPositions(int currentPos)
{
yield return null;
}```
you would combine a while loop with Vector3.distance to each point, dont put start coroutine in the loop
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Yielding a coroutine means the current coroutine stops until the new one finishes. I'm assuming you plan to add more stuff to the second one because right now it's got no purpose at all.
where would i put the while loop?
yeah i do
inside the coroutine
so I shouldn't use the second coroutine for this?
don't see a purpose for it
i had a problem earlier where the objects were moving so vector3 didn't work, but i changed the object so this shouldn't an issue anymore
idk what any of this means
sorry im rambling
first worry about how you scroll through an array/list
that would be the first step
sorry i just thought about this but why would i use a while loop instead of a for loop? Wouldn't it be better to move to a position for each item within the list?
what youre trying to do is starting a coroutine for each point on the same gameobject? how will it know which one to go to if they're all starting at the same time to different points
i deleted the second coroutine, now its just one coroutine with a for loop inside
why do you need a for loop I dont understand
are you controlling multiple objects?
no just one, think of it as a ball
ok so it doesn't need for loop
im confused
my impression is that when the coroutine starts, the ball will do a thing for each item within the list
you tell it to go to point A, when it reaches point A you tell it goto point B
rinse and repeat
the problem is that i dont know how many points will be in the list when the coroutine is started
its not the only ofc you can literally just give it a list of tasks to do , there are many ways to do something
would it be okay if i explained what im trying to do a bit more so there's no confusion?
exactly why you shouldn't care about all of them, just the one you're going to
lets make a thread
sure
can someone explain the following error to me?
Main Camera: 1 camera overlay no longer exists and will be removed from the camera stack.
I was using 2 overlay cameras (screenshot 1), and as soon as I enter play mode one of them is gone... (screenshot 2)
the error comes from the "Universal Additional Camera Data" script in line 462. (not written by me but added to cam automatically)
Is it an error
Or is it just a log saying that it removed the camera from the stack? Presumably because you're Destroying it somehow
I've been struggling for weeks with MonoBehaviour instantiation but I've always just ended up finding workarounds, but now I'd really just like to use new() to create a new object of a script, but I can't because that script inherits from MB. Can someone just really quickly guide me through how I can imitate this exact behaviour but with AddComponent() or whatever other method I need to use?
Instead of calling new() call AddComponent
You cannot imitate the exact behaviour, you can only create a method you call after using AddComponent
Add the component to the object you want to
I'm trying to instantiate a prefab from a scriptableObject but for some reason it's giving a NullReferenceException. I have everything assigned in the inspector so I'm having a hard time figuring out where it's going null.
The line that instantiates it but throws an error is: Instantiate(weapon.equipment);
and the class it pulls from is written like this:
public class EnemyWeapons : ScriptableObject
{
public GameObject equipment;
public Vector3 weaponPos;
public float fireRate;
public int bulletsPerShot;
}
Does it matter what object I choose? I have a Main object that's currently just holding scripts so I'd prefer to use that
It'd be whatever object you want the component added to
What line throws the error
"The line that instantiates it but throws an error is: Instantiate(weapon.equipment);"
Debug your weapon and then weapon.equipment
I don't want to use any components really, I just want to call a function from a Dropdown menu, which has a script called DropDown.cs, and I just need to call a method within that script from another script.
Would it, in that case, matter where I put the component?
so why is it a monobehaviour
The script is a component in my Main object that is holding scripts
It is so that I can do this
So it already is a component on an object
why are you trying to add it to another object?
Debug what specifically though, as far as I'm aware, there is no other point in the code that could be causing an issue because this is the only part that isn't just a variable.
I don't want to add it to another object I just want to grab a public variable from inside it (non-static) for which I of course need an object reference
Okay so why are you asking how to add it to another object
if you don't want to add it to another object
I just wanted to use new() to create an instance to get that variable
Literally all I want to do is get that variable from the other script
why
you have an instance
use that
Sorry, I'm new to Unity. Does having the script as a component on an object instantiate it?
it creates an instance
of the script
GetComponent usually
Serialize the Main gameobject?
yeah when possible always make fields in the inspector, and assign that way
I'm guessing that for my situation serializing the object would work fine and wouldn't be worse than getcomponent
Yes, debug exactly that. You want to check if the weapon object itself is null, if it isn't then perhaps what you're accessing on it is null.
in that order
So let's say I'm going to [SerializeField] GameObject main (that's how I would do it, right?), how would I access the script that is a component of that GameObject?
no you serialize the type for the script
Why would you reference the game object instead of the script you actually want
^ this. Every Monobehaviour has access to their own gameObject& transform already
The weapon object isn't null or at least doesn't have a reason to be as it is attached in the inspector, and same thing with the weapon prefab.
What line is throwing the error
The name of the class is the type.
public class Foo : MonoBehaviour { }
public claas Bar : MonoBehaviour
{
[SerializeField] Foo foo;
}
this: Instantiate(weapon.equipment);
Then weapon is null
but weapon.equipment isn't null
So I have a GameObject, which has a component that is a script, that contains a public variable that I need to access. How would I [SerializeField] a component of a GameObject? I didn't know that was possible.
Don't always trust the inspector. Always debug your values
That screenshot doesn't show weapon
You would [SerializeField] the component you want
this does
This shows that one instance of this script has weapon
they even thumbs up and asked the question xD
Got it, thank you. I didn't even know you could drag and drop components from the Inspector! I have a loooot to learn 🤦 Thank you all for the help
It's the only instance I have though
You almost never need a GameObject variable. You can even instantiate an object by referencing the script on it. It will also instantiate everything else along with it
it was in the page you were linked
on weapon or the script that instantiates it
On the script that is throwing the error
omg
i'm so dumb
I dragged it onto my canvas at some point
💀
i'm offically quitting gamedev
This is why you always check
The errors can not lie. If it says you have one of these scripts with weapon null, then you do. It's up to you to find out where
Fair enough I just assumed I had perfect knowledge of my scene
I guess I just accidentally dragged it to the wrong thing at some point
ok thx
yeah sorry i was destroying it unknowingly.. I thought unity was destroying it for some reason so i came here
private bool isGrounded()
{
RaycastHit2D hit = Physics2D.BoxCast(coll.bounds.center, coll.bounds.size, 0f, Vector2.down, 0.1f);
Debug.Log(hit.collider.gameObject);
return hit.collider != null;
}
does someone know why the boxcast hits the player instead of the ground
Why would it not? You have applied no logic to make it not do that
but I directioned the cast down so it should it the ground
i keep getting this error but I have no idea why, can anyone help me understand what might be causing it? Full script here https://hastebin.com/share/azizoyikuw.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
everything in the coroutine has a reference to my understanding, really stumped
Check the values and see which one is null
how do i do that?
Using the debugger, or logging
which value should i be checking exactly?
im trying to make an animation start thru collision of a box collider and the animation just won't play
could it be a code problem?
The ones that can be null on the line where the error's being thrown from https://unity.huh.how/runtime-exceptions/nullreferenceexception
so everything in the coroutine that can be null?
If you're confused, go through the resource I linked
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimTrigger : MonoBehaviour
{
[SerializeField] public GameObject player;
[SerializeField] private Animator anim;
void OnTriggerEnter(Collider col)
{
if (col.gameObject == player)
anim.Play("LiamWalk");
}
}```
is the object that has the script set as a trigger?
wdym
so the object that has this script should have a collider component
Have you checked whether the function is being called at all?
is the option "IsTrigger" on that component ticked?
yes through the console, and its not
Go through the physics message debugging resource that is pinned to this channel
it should become clear pretty quickly what you've done wrong
my code would still work the same if i used either col or collider right
@north kiln im trying to debug stuff but i dont really know what im doing even after reading the thing you sent
Whats the best way to implement a messages log box with a max amount of messages?
Something similar to the picture is what im looking for
how do i know what thing i should be debugging?
You know what line it is because of the stack trace, and you know what the reference types on that line are, so check all of those by logging before that line
a simple List<string>
im not sure where to find "d__8.MoveNext" in my error
LETS GO
apparently thats the method
lockOn is the class
MoveNext, sounds like a coroutine
and :40 is the line of code
only problem is he still starts his animation on his own automatically even though "Play Automatically" is ticked off, what do i do
and then BailiffMove is the coroutine, but i dont have MoveNext anywhere in my code
but thats just referencing the line that starts the coroutine
can you show Line 40
if (Vector3.Distance(throwB.newBall.transform.position, hitList[currentHit].transform.position) < 0.8f)
You have changed your code since that error
i just added a debug.log
throwB throwB.newBall hitList hitList[currentHit], one of these is null at some point
where did you assign throwB
throwB is a reference to a class, its at the very top of the script
this one
That's a declaration, not a reference
thats declaring
oh sorry
where did you assign
im not sure i understand
Though, I have no idea how it got to line 40, surely DiscThrow is a struct if it got there?
let me send the discThrow script too
how do we assign a value in code ?
thing = amount
🤔
you just said = assigns something, this isn't assigning
christ im dumb
yeah its private, but that has no affect in assignment
man im really confused, does something need to be assigned to that?
if i remove the animator, it doesnt play the animation at all but it cant run without the animator
surely it just needs to be declared and thats all?
how does it know which DIscThrow instance you want
DiscoThrow is meerly a blueprint
there's only 1 DiscThrow, and im referencing a variable from inside that class, how come that doesn't work?
How is the code supposed to know which Disc throw you want
there can be 1 or 0 or millions, it makes no difference to the computer
it wants to know which one of these you wanna get/set this variable from
it would be kinda counterproductive if it magically plugged itself in
okay lets assume that its newBall because an object is being instantiated there
how would I specify which newBall i want to reference?
you're assigning a new ball to an object that doesn't exist
maybe brush up on what an actual instance is
am i misunderstanding what an instance is?
you're probably confusing it with Unity's Instantiate which is somewhat similiar
what is the difference between Instantiate and an instance?
i thought they were linked
In regular cSharp you have to create an object from the blueprint (class) you defined
thats an instance
MyClass foo = new()
foo.Something()
foo is the instance itself
in unity a script is a component which creates an instance when its on a gameobject
so you can't new() monobehavior classes
this makes no sense to me
i understand a script is a component
but how does it create an instance when its on a gameobject?
it just does it internally , not something you should worry
but yeah because you cannot new() a monobevahoior , to use the instance you assign the one on the gameobject
i think i understand monoBehaviour, its inheriting values from another class called monoBehaviour
public class LockOn : MonoBehaviour
yeah
yea : inheriting
my lockOn class is inheriting certain values from MonoBehaviour
properties and methods
right
so whoever has LockOn script on they have that instance
depends on your animator 🤷♂️
i need my sprite to stop animating as soon as i start the game
so then i dont understand, why am i getting an error for newBall even though it hasn't been instantiated yet?
but i have no clue what im doing wrong
did you start it with an empty state?
because I told you its not newBall lol
this is what my animation things look like
newBall is being assigned to an object that doesn't exist (as far as the computer knows)
is my animation tree the problem
dont use animation first of all lol
that component has a mind of its own lol
but why? newBall is assigned in the throwB script
you need to make states inside your Animator
oh
Scripts are not objects
they're just blueprints to an object
like a collision trigger?
or bool?
no like you put an idle state , empty state, whatever other animation inside then control them via parameters
follow some beginnner courses on animator
im really confused. The way I see it, the newBall variable in the DiscThrow script is being assigned the discPrefab object. What doesn't work there?
Where is it being assigned
you're confused because you're missing the basics tbh
throwB.newBall = Instantiate(throwB.discPrefab, throwB.discSpawn.position, throwB.cam.transform.localRotation);
you have to understand the difference between references and declaring
Where is discPrefab being assigned
in the ThrowDisc script
Show that
Am I missing something, where is throwB assigned? In the inspector?
is throwB throwing null btw
Actually yeah
hold that thought
Where is throwB being assigned
{
public GameObject discPrefab, newBall;```
they know that assigning is = but somwhow this is missing the spot
That is a declaration, not assignment. Just to be clear
Okay, so this is public. Is it assigned in the inspector?
{
// MAKE CLASS A SINGLETON
public List<GameObject> hitList = new List<GameObject>();
private DiscThrow throwB;```
So where is throwB being assigned
Where do you assign then though?
That is not an assignment, it is a declaration. Something completely different
i believe so
Let's close the door on this avenue for the time being. Where do you assign a value to throwB
💀
Don't believe. Confirm. Just look at the inspector
Does it say "none"? Or the name of an OBJECT?
you literally have to do the same thing except that Unity has option to also use inspector, but not if the field isn't serialized to expose it and assign it there.. @muted wadi
Simple question: Where do you assign throwB
Just show the inspector for the object already
like telling someone I have a have a party at my House and guest ask where is your house, and you reply.. "House"
Where do you tell the code which GameObject throwB is
i dont think i understand what you mean by that honestly
You have a variable called throwB
What object is in it
Time to go learning some C#/unity basics!🪄