#๐ปโcode-beginner
1 messages ยท Page 420 of 1
I was trying to check if rightleg or leftleg collided in the same script thats why I asked
if you put it on a parent rigidbody and you have both colliders on each leg you get the trigger message
what are you trying to do exactly
wdym " rightleg or leftleg collided in the same scrip"
are you trying to ignore collisions between the two ?
No
If the right leg collides a bool will turn true , if left leg collides other bool will turn ture
gotcha
But I wanted to check that in their parent gameobject
Because I have a script about walking in parent
Would this work in that case?
iirc inside the parent object you have no way to determine which one called the collision
only the rigidbody of those colliders
or the collider hit
if you put script on each leg then send a message into a parent script, you can probably do that
How do i assign?
nice tnx
your issue is your missing brackets, which is why i said to configure your IDE
my IDE have the unity extension
jn
there are several steps involved
are you using the VSCode one
are you ok Random lol
i use vs code
!vscode
follow this link
anyone know why DelayStart isn't activating and instead it's just spamming "start"
!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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
that is also not how you call a coroutine (look at the 3 dots on the method, Visual studio is trying to help you)
oh damn
The only thing printing "start" here is the Start function. If that's getting spammed you have a bunch of instances of this script being created
wdym it's I spelt it right?
the one on update is wrong
apparantly there's no objects
send them a selfie with your code 
like this ?
also this would probably call StartCoroutine everyframe if ballcount >=0, bad idea..
oh I thought I put less than
I am a fool, I know nothing, I take the role of a silly clown.
what is the problem
they're missing brackets it should be lighting up like a xmas tree
i don't have an 'input box' to choose objects?
ideally to configure their ide
where ??
you have compile errors
Do you have any compile errors
shouldnt be that bad if the missing bracket is on the last
thats why i said configure your IDE ๐
but yea, c# dont care
!ide please do this first
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
the fields and methods aren't even inside a class though lol
Are those lines underlined in red in your IDE
well, vsc is smart enough to consider them inside
nop
but i have download the unity extension
you have an opening bracket though dont you ?
oh tf they dont lol
Then you, absolutely, 100%, definitely need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
yeah all the fields would be like xmas right now lol
I made a Capsule in unity 3D. I then rotated it on the Z axis by 90 degrees. what I want to do is point the Y local axis green arrow of the game object towards another game object. how can I do that in the code
You can actually set transform.up to point an axis in a direction. Get the direction to the other object and then set transform.up
||transform.up = (target - myPos).normalized||
ive been having so much of an issue figuring that out and you gave me a simple straight forward line of code that fixed my issue thank you!
also thanks to you as well for explaining it all to me
anyone know why when I move objects in the editor they only go a fixed distance?
like I drag a cube and it goes x=1, x=2, x=3 when I'm trying to do x=1.5
this isn't a code question
wrong chat mb
thanks
Does GetComponentInChildren work if the children arent enabled?
https://docs.unity3d.com/ScriptReference/Component.GetComponentInChildren.html
the docs tell you, and also show a parameter related to that
Heya, does anybody have any pointers on why my windowed fullscreen (borderless) has the same exact behavior as exclusive fullscreen? Are there any issues with changing between them at runtime? Windowed and exclusive fullscreen work perfectly though
My code:
public void OnScreenModeChange(int index)
{
switch (index)
{
case 0: // Fullscreen (Exclusive)
Screen.SetResolution(Screen.currentResolution.width, Screen.currentResolution.height, FullScreenMode.ExclusiveFullScreen);
break;
case 1: // Windowed Fullscreen (Borderless)
Screen.SetResolution(Display.main.systemWidth, Display.main.systemHeight, FullScreenMode.FullScreenWindow);
break;
case 2: // Windowed
Screen.SetResolution(1280, 720, FullScreenMode.Windowed);
break;
}
}
Thanks!
https://docs.unity3d.com/ScriptReference/FullScreenMode.html
are you on windows? ExclusiveFullScreen is windows only
Yes sir
are you sure they're functioning the exact same, and just to be clear you're testing in a build right? im fairly certain one of them should be quicker for switching with alt-tab
Yeah I tested in a build and they're both instant when I alt-tab if the game is the same resolution as my system, and they are both super slow when I alt-tab if the res is different from my system res
It might be working and I am just not noticing the difference haha
but it feels the exact same
Not entirely sure how to link an exact reply from the unity forums, but the comment from Ryiah
This is really interesting! Thanks a lot for linking this
So real exclusive fullscreen doesn't exist with directx 12, so I'll just not include it as a feature in my game
i gotta test in my game too because i included it as a setting ๐
The forum posts say that even if it works it is faked and doesn't give any performance benefits in windows 10/11
nice find on the thread
thanks dude
its weird because I do recall other games having these options, now i know at least it doesnt matter if i choose it
how do i make it so that i can get a component from a gameobject script and make it a string on the script im working o
make what a string, and what part are you struggling with?
I am making a tag based game and im new to scripting so i put "tags = GetPlayerTags.playertags" with a public gameobject GetPlayerTags at the start
a gameobject doesnt have a .playertags,
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
get the script you want then use whatever you value you want from the script
or just directly drag in the script rather than storing a game object, so you dont need get component at all
What does "tag based game" mean
99% sure its a gorilla tag mod or clone
a game where the main focus of it is tag
What do you mean by tag
here we go again 
mod
Like tag youre it?
omg
modding discussions arent allowed in the server, so you'll need to ask in the games server/modding server if they have one
I need help with that I dont understand this at all
before modding you should probably learn how to read an API
Start by learning the basics of Unity
im not mod
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
alr anyway start from beginnning
CAN SOMEONE JUST HELP ME plzzzzzzzz
you dont have to watch all the videos obviously
hard to help someone who's not willing to help themselves :\
just tell me what to type instead plzzz
what good will that do ? you wont understand where it will go or what it does etc.
Nobody really knows what you're talking about or asking to be honest
I will learn just plzz help
so start with the link sent to you
I need to grab a component from a script in a gameobject how do I put that oin "tags = GetPlayerTags.playertags" dosent work bc its not right
yes you can't write random stuff and expect it to work
already told you what you need to do, if you dont understand what i wrote then you must start more with the basics.
im blockin this kid
Go ahead, im the only one thats probably given you resources for help. Its not like this is the first time you've spammed and begged for help with the most basic of c#
Bawsi has given you the answer
Like the actual, exactly what you need to do answer
well that's just childish. They've been helpful and you're being a whiny baby
To be fair, they are a child so i dont really expect more
Terrified of the day my daughter is a 12 year old, like they are.
Hopefully they won't act like they do, but ๐คทโโ๏ธ
yeah but common sense and matters should exist early... my nephew is young he certainly dont act this way
Might as well give up then. You can't learn gamedev in 30 minutes.๐
rolls up sleeves . . .
People are saying this to you because they are more experienced than you, and know that new people most of the time start too big instead of simple cube and spheres games. You're trying to mod a multiplayer game which is even harder
rolls down sleeves . . .
how do i make something happens when a string says aspecific word or number
i didnt block you genius
Drop the tantrum
You have to define the rules of what you consider to be a specific word or number. Does casing matter, does it just have to contain the words/numbers, or be exact.
i want an object to be enabled when my string says "10"
Ah, a string. Read that wrong
yea
Where is the string coming from? Are you converting it FROM an int?
If not, you gotta parse it
It it is, skip the string and check the value
I guess you could compare the string directly. I avoid string as much as possible, but I wonder if just myString == "10" would work.
It should
Here for parsing though
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/how-to-convert-a-string-to-a-number
Ty this helped so much
help, suddenly I cant change the rotation and scale of a child object while the game is running, in this case the sprite is a child of the player
A script is probably restriciting those changes
I got a camera attached to a player object in 3D and using this:
cameraTransform.position += cameraTransform.forward * scroll * 1000 * scrollSpeed * Time.deltaTime;
to scroll the camera in and out from the player's look direction. How would I clamp it from going through the player?
It only has this script, and yesterday used to work just fine, today I havent touched it but it stopped to work
(Quaternion newRotation = Quaternion.Euler(0, 180, 0);
Sprite.transform.localRotation = newRotation;)
Can you show me the full script so I can show you exactly how to do it using Mathf.Clamp
!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.
check (and restrict) the distance between the camera and the player . . .
here's the full code
no, use the links . . .
oop sorry
Not much to the whole script relitive to this
There's a public Transform cameraTransform;
then this
// Handle scrolling
float scroll = Input.GetAxis("Mouse ScrollWheel");
cameraTransform.position += cameraTransform.forward * scroll * 1000 * scrollSpeed * Time.deltaTime;
not everyone (mobile) can see (access) that . . .
Try something like this
scroll = Mathf.Clamp(scroll, min, max)
(The float scroll part is what I needed to see)
I believe that would only limit the speed and not the actual position, no?
but wouldn't that allow me to like scroll out, but then not back in due to clamping the input part?
I think it should work, try it
I think its a number so it should be fine
Sorry for being so vague im unsure how to explain it properly
But yeah since its using position, it wouldnt be accurate
as you can see, it only has the controller script, and yesterday it worked fine
I did something similar to this in my own game so im trying to remember
@mint remnant you mentioned that you had "attached a camera to the player" - by that, do you mean that the camera Game Object a child of the Player Game Object?
yea, that didn't really do much, I think what @cosmic dagger suggested might be along my best options
Yeah mb for bad advice
yea, main camera is a child of a playre object
Cool cool - then I think cameraTransform.localPosition should be representative of the camera's offset from the player... You may be able to just Mathf.Clamp() or Mathf.Min() the z component therein
a compicating factor is I also have code that allows mouse movement to rotate the camera, but I may have to re-think scrolling with the rotating as that can make it so the scroll vector might not be aiming in a constant direction
why i can't rotate a object when I hit play, it only has Sprite Renderer and animator
omg i found the error, it was the animator "Apply root motion"
Which channel would be best for an extremely simple GitHub Desktop question?
Mainly I just learned how to use the repository for my first time and I'm wanting a better explanation of what "Fetch Origin" means than what I'm seeing online. Also once you publish a project to GitHub does it continue to update as you make changes in GitHub Desktop? Or do you need to repeatedly republish it to GitHub? (Is that what a push is, isn't it?)
Online I'm seeing Fetch Origin to mean that it "fetches" data rather than "pulling" it into your code, but idk what data they mean or whn/why I would ever use Fetch Origin.
TLDR: When would you use "Fetch Origin" and why? Is it only for group (and not solo) projects?
it's been a while, but you have to remember you have a local repository and the one on gitHub, you can commit changes to local, but then I think only on a push does it update the gitHub one
fetch origin basically just checks if theres any changes. yes could be more of a group thing, but you can also see it work if you add a change through the github website
also compare to git rebase
Also once you publish a project to GitHub does it continue to update as you make changes in GitHub Desktop? Or do you need to repeatedly republish it to GitHub? (Is that what a push is, isn't it?)
It only updates what you push to it. With github desktop its really just a matter of pressing 2 buttons but in reality you're adding the changes, commiting them along with a message describing the commit, then pushing them to the repo. You can commit many times before pushing, but this would only be local (on your computer, not shown on github)
i have a rq question so I'm making a Game manager to help keep track of the game state and to do so i need to change states based off of if all the enemies were killed so i put all enemies spawned in a list and checks when it hits 0 to change to state 2 but then in state 2 there saved to the same list and when that hits 0 it keep repeating so I'm wonder should i create a bool to check if the state in currently is the next one or should i just make a list for each new state?
this makes no sense at all, try reading what you just wrote.
should i create a bool to check if the state in currently is the next one
its all one sentence. take a moment and clarify, show code if needed.
i have a rq question so I'm making a Game manager to help keep track of the game state, However to do so i need to change states based off of if all the enemies were killed. so i put all enemies spawned in a list and checks when the list hits 0 to change the state to the next one. Then in state_2 All the enemies are saved to the same list as in the first one. so when that hits 0 it keep repeating. so I'm wonder should i create a bool to check if the state in currently is the next one or should i just make a list for each new state? here code if needed https://gdl.space/ujiyurexux.cs
first thing, dont add me. read the server rules, i wasn't gonna answer any questions in dms.
2nd thing, adding periods between doesnt change that some of these sentences just dont make sense.
not really part of your question, but you shouldn't if check a 2nd state if you checked one already. Switch to and if else tree or even better use a switch case scenario
oh sorry i thought thats what confused you what are you confused abt?
you might want to include in this statement if (SpawnedEnemys_1.Count == 0) something like && GameState == GameState.Whater
ok thank you ill try that out
the main concept of a state machine is it has defined states and you can only move from one state to another, so let the state machine do the transitions, and draw out a state machine diagram to make sure you stick to it in code
ok thank you sorry still trying to make this first game totally alone
i directly quoted above a part that didnt make sense. #๐ปโcode-beginner message
You might wanna define more of when you want this logic to happen. Like in what states should it even check the count of the enemies and then go to state phase_one
you should probably be following some tutorials or guides, because just blindly going through this will be unmanageable. This code is extremely fragile
Is there a delay between setting a variable and being able to use it?
nope
you'll need to show context if you're having an issue,
on what you're doing
im kinda following one but again this game is totally different, and im making one on my own this time to get more of a feel for it.
if you're doing multi-threading you could set a variable and another thread might change it before the next line
one thing you should definitely try to do is set this up so it can be filled in the inspector. Right now if you wanted to add a 4th boss, suddenly you have to go add more code. If you had an array or list of gameobjects/transforms then you could loop through it and spawn based on that.
If you ever find yourself doing Boss1 Boss2 Boss3, you could likely be using a list instead.
yea im prolly gonna do that now that you bring it up
https://gdl.space/paniyofuzu.rb I'm making an animator but i need a way to make it so when the player stops pressing WASD respectivly it sets the bools to false and floats to 0. Any ideas?
btw its in update
Input.getkeyup?
Nvm, fixed the issue. Short version is that I had my SplineAnimate script disabled from the start; so when I enabled it to play the animation, it had to go through its start-up code which led to the Play method not working correctly until its start up code was finished.
I tried that it just made the If() functions not work at all
or getkeydown?
For all of those ive tried there repective keys. Dont work
ok so your issue is when you stop pressing keys you want it to set all of the bools to false and floats to 0?
correct
does your character face 4 different ways?
Also just realized that it's wrong to be setting velocity directly.. which is what I've been doing for most of my projects.... whoops
this might be a strech but it might work try setting an else that sets it back to 0
Nothings wrong with it
I heard it was a bad practice to set velocity directly.
I tried that. It just keeps the last animation it was on going and cant change it
People will say everything is bad practice. It's totally valid to set it directly, if you want to be directly controlling the velocity at all times
Im gonna tackle this tommorow im goin to bed
thank you
ofc and rq if this is to much try looking into using GetRawAxis to get horizontal and vertical bc it most likely work after that
It's not good if you don't know what you're doing ||- modifying the velocity of the rigid body object||
Omg youโre so fuckin right thank u bro
For example: modifying velocity-y every frame but wondering why gravity isn't working properly - same applies for directional forces being applied to the object.
Why doesnt this work together?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed = 5.0f;
public float mouseSensitivity = 100.0f;
private float horizontalRotation = 0.0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
Vector3 movement = Vector3.zero;
findObjectOfType<grounddetection>().Getbevegelse();
if (Input.GetKey(KeyCode.W))
{
movement += transform.forward;
}
if (Input.GetKey(KeyCode.S))
{
movement -= transform.forward;
}
if (Input.GetKey(KeyCode.A))
{
movement -= transform.right;
}
if (Input.GetKey(KeyCode.D))
{
movement += transform.right;
}
if (Input.GetKeyDown(KeyCode.Space) && (isColliding==true))
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 300);
}
transform.position += movement.normalized * moveSpeed * Time.deltaTime;
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
horizontalRotation += mouseX;
transform.localRotation = Quaternion.Euler(0, horizontalRotation, 0);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class grounddetection : MonoBehaviour
{
public bool isColliding = false;
void OnCollisionEnter(Collision collision)
{
isColliding = true;
}
void OnCollisionExit(Collision collision)
{
isColliding = false;
}
void Getbevegelse()
{
return isColliding;
}
} ```
"Doesnt work" is incredibly vague, what doesnt work specifically? Also !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.
findObjectOfType<grounddetection>().Getbevegelse(); guessing it failed to find that object
configure your !ide if you arent seeing these errors in there
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
yea something really wonky, if you're getting win32 compile errors
no need to guess, if you read the actual errors this isnt close to the issue
theres just basic c# mistakes, misspelled function name and also 2 of those errors seem to be in different scripts
anybody know if/how i can save data from my scene into a file with a script
if it's small data maybe look at playerprefs
I know this is stupid but I can't figure how to get the velocity.
is there a way to make all boxcolliders visible in scene?
BocColliders is an option in Gizmos drop down
Noooo
Regardless of size, PlayerPrefs should be considered a temporary solution
hi guys need help regarding ads, i have tested the ads it is working but after build the real ads are not showing what to do??
You can start your PS from a MonoBehaviour with Play() https://docs.unity3d.com/ScriptReference/ParticleSystem.Play.html.
IIRC there is an autoplay option in the PS that you should disable and then you control it from your behaviour so that you can start, pause or stop the playback whenever you want.
yeah there's a "Play on Awake" box for each particle system
there is a start delay.
Is this what you're looking for? I dont think you were asking what the above responses were for https://docs.unity3d.com/ScriptReference/ParticleSystem.Simulate.html
This is how you can start it "later"
Oh yes, I may have misunderstood the "later" here.
by changing the start delay timer using script.
At least yours was the closest, the other 2 answers pretty much had nothing to do with the question
Assuming they get back to us on if my interpretation was correct
Hi. I've been trying to solve my problem over the Internet for an hour now: I want to use void onMouseEnter, but it doesn't work at all. I've already simplified everything to Debug.Log(), but it still doesn't work. On the Internet, I saw that I needed to change the Input System to New or Both (New does not work and set Both - as they said on the Internet). I'm already tired of all this. How to solve this?
Ah I forgot about that option. Also for the future there is a channel #โจโvfx-and-particles
put the collider for the box.
I didn't understand what you meant, but I was recreating the object and its collision. Nothing helps anyway.
i dont think that object has any collider. without any collider it will not detect any mouse enter or exit or etc.
I don't see it on screen but I suppose your Quest script is attached to this same cube ?
And, you need to attach a script to the object itself, not to the camera... Thank you. I'm sorry I was dumb.
you can also reference it if you want it on camera.
It's alright, that's how you learn ^^
I have an issue here that when the parent object turns 180 in y, the aimObject gets flipped. How can I fix this?
Vector2 direction = GetJoystickDirection();
if (direction != Vector2.zero)
{
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
aimObject.transform.localRotation = Quaternion.Euler(0, 0, angle);
// Flip character based on aiming direction
if ((angle > 90 && angle < 270) || (angle < -90 && angle > -270))
{
transform.rotation = Quaternion.Euler(0, 180, 0);
aimObject.transform.localRotation = Quaternion.Euler(0, 0, -angle);
}
else
{
transform.rotation = Quaternion.Euler(0, 0, 0);
}
}
Children objects will inherit transform changes from the parent object. Are you sure you want to set the local rotation instead of just the .rotation?
I just changed it to .rotation
It doesn't rotate tho, I think the Y Rotation is wrong
Are you sure the code is running? Or are you sure you understand what it's doing. It would only look like its rotating if you're actually changing the direction, because you're just setting the rotation directly
Yeah, it is running. I changed the code to this as I though if I can just flip it 180 when the entire parent flips, it might work. But for some reason, the value becomes -180?
if (isAimingWithButton)
{
Vector2 direction = GetJoystickDirection();
if (direction != Vector2.zero)
{
int num = 1;
int xValue = 0;
if(transform.rotation.y == 180f)
{
num = -1;
xValue = 180;
}
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
aimObject.transform.rotation = Quaternion.Euler(xValue, 0, angle * num);
// Flip character based on aiming direction
if ((angle > 90 && angle < 270) || (angle < -90 && angle > -270))
{
transform.rotation = Quaternion.Euler(0, 180, 0);
//aimObject.transform.localRotation = Quaternion.Euler(0, 0, -angle);
}
else
{
transform.rotation = Quaternion.Euler(0, 0, 0);
}
}
}
In my game I need to change the player's gravity a lot. It is affected by player's jump and some status effects, for example. I want the changes to stack together. I have a list gravityMultipliers, where i add and remove them during the game. The gravity is then multiplied by each of them. Is this a good approach?
Are you looking at the values in inspector? You shouldnt be if so. The values shown are local rotation and converted from quaternion to euler
Yeahh but I don't understand why the AimObject is getting flipped upside down when I flip the character. I am doing -angle so shouldn't it point to the right side?
It is pointing to the correct side, I mean, it's vertically flipped though, the gun becomes upside down
Im not sure what you're setup is like so idk what the left or right side is (and plus I dont have the time to see it rn). But a lot of your code has logic flaws
You shouldnt be reading the y component of a quaternion, it isnt what you think it is. Even reading euler angles isnt consistent, they are converted from quaternion. Keep track of them yourself if you want to stay with euler angles
Theres not really much to say here, if you want a list of gravity multipliers then yes you need a list of them.
Dont crosspost, read the server rules
Facing Right vs Facing Left
This is the only issue I have ๐ The Arm with Gun is a child of the Player Object
I feel like you could just use LookAt here though not sure how 2d works myself. Or even like Quaternion.LookRotation
I fixed it
hey how can i switch my scenes in code? i have the using directive but sceneManager.LoadScene() doesnt work
"SceneManager"does not contain a definition for "LoadScene"
then you have the wrong using
using UnityEngine.SceneManagement
do you have your own script called SceneManager ?
no
in that case it should work
try UnityEngine.SceneManagement.SceneManager.LoadScene()
i just have a script called UI where all functions are contained used for buttons
but it doesnt
doesnt work
if you hover over SceneManager what does it tell you?
then something is wrong with yourproject
class SceneManager
you probably dont have it configured properly
it will tell you a bit more than that
no it doesnt
which ide are you using
thats weird i just have class SceneManager
what is ide?
then you DO have your own SceneManager class
visual studio
oh wait
its not configured then
probably bc of my assets from the asset store
go in your project settings and set visual studio as your ide
it is
its not if you cant access it by full path including namespace
in visual studio open the sln file
instead of the folder
i dont like this
that shouldnt be the issue
this should work
but it doesnt
can i rename a script if i change the class in the code too?
best not. add the following to your script
using SceneManager = UnityEngine.SceneManagement.SceneManager;
i renamed it using ctrl r ctrl r it works now๐
can you show whats in that file
it shouldnt be able to override the unity scenemanager
should be in a different namespace
https://gdl.space/ejeyuwawoh.cs ignore the [System.Obsolete]
i think you didnt write what we told you correctly or something
Bad asset. ALL assets should put code into namespaces to avoid just this kind of problem
what we wrote should work
indeed, both your suggestion and mine
yeah but it seems kinda like ductape to me. just renaming the class causing the problem is the better variant ig
tbh that looked like example code so you could have just deleted it
yeah ik but i had to much panic to just delete it even tho it shouldnยดt change anything haha
I would send a message to the asset publisher btw, to inform them to put their code into a namespace
or report the asset on the Asset Store as that is now a requirement for ALL assets
Trying to make a simple FOV slider, but am getting the error "MissingComponentException: There is no 'Camera' attached to the "PlayerController" game object, but a script is trying to access it."
I have my FOV script applied to my PlayerController GameObject, and the image provided is the way I have my player put together.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FOV : MonoBehaviour
{
public Camera PlayerCamera;
public float playerFOV = 60f;
void Start()
{
PlayerCamera = GetComponent<Camera>();
}
void Update()
{
PlayerCamera.fieldOfView = playerFOV;
}
public void fovSlider(float zoom)
{
playerFOV = zoom;
}
}
Isn't the camera on the child object FirstPersonCamera?
And since it's a child then just drag it into the field in the inspector, no need for extra code if the component is accessible from the get go
You don't have a Camera component attached
You also don't need to change the field of view in an Update. You can just change it in the fovSlider function. So you aren't setting it every frame
camera fov is finally working like it was before (sitting at 60 normally), but when i use the slider its not updating the actual camera's FOV. any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class FOV : MonoBehaviour
{
Camera maincamera;
public float playerFOV;
public float minFOV = 60f;
public float maxFOV = 90f;
void Start()
{
maincamera = GetComponent<Camera>();//sets the Main Camera as the variable
playerFOV = maincamera.fieldOfView;//sets playerFOV variable to the Main Camera's current FOV
}
public void fovSlider(float zoom)
{
maincamera.fieldOfView = playerFOV;
playerFOV = zoom;
}
}
use Update or FixedUpdate.
lol,
maincamera.fieldOfView = playerFOV;
playerFOV = zoom;
wrong way round?
public class FOV : MonoBehaviour
{
public Camera playerCamera;
public float playerFOV;
public float minFOV = 60f;
public float maxFOV = 90f;
void Start()
{
//playerCamera = GetComponent<Camera>();//sets the Main Camera as the variable
playerFOV = playerCamera.fieldOfView;//sets playerFOV variable to the Main Camera's current FOV
}
void Update()
{
playerCamera.fieldOfView = playerFOV;
}
public void fovSlider(float fov)
{
playerFOV = fov;
}
}
idk anymore, this wont work
it just seems like its not linking to the slider and i dont understand how to fix it
did you applied that method on the slider.
hey how can i add a little delay in my code?
fastest method would be to use StartCoroutine.
Start() {
StartCoroutine(Wait());
}
IENumerator Wait() {
yield return new WaitForSeconds(1);
// do stuff
}
Your value is fixed to 60
how
i have a min of 60, max of 90, and the player's current fov which is changed
Under the method name there is 60 clearly visible. It means it will always fire the method with 60 as a parameter
so how do i get that to change?
because nothing im doing is linking to that value and idk how to access it
i want to link the value, to the slider component's value
Look in the methods dropdown, there should be the same method option in dynamic section (the top one)
all this time
it was because
i didn't select the dynamic option
that i had no idea
even exited
hello. trying to get a random # from 1-100, but getting error "cannot declare variable of static type 'random'"
do this playerCamera.fieldOfView = slider.value;
this is not needed
this worked, thank you so so so much
Are you intending to use Unity Random or System Random?
You would not be able to create a new instance of Unity Random, if intending to.
I tried googling this and honestly just got confused. I dont believe the differences matter to me?
Unity random is not a C# class. you're trying to use System.Random. you need to qualify the namespace . . .
it does, hence the error . . .
I'm informing you so because that is your current error - you're using Unity Random but trying to create an instance as though you're using System Random.
yes
Just use:
public void SomeMethod()
{
int rng = UnityEngine.Random.Range(1, 101);
}```
int randomValue = Random.Range(1, 101); to get a random number 1-100 inclusive
no errors, thank you!!!
Reminder that you would call that line whenever you need a random value and not just assign a variable a random default value.
what is the difference between
public static bool & public bool?
one is static
making something static means it's not bound to an instance. A static field/property/method doesn't need your class to be new()'ed, for example.

static public List<string> characterDatas = new List<string>();
static public void ResetData(){
characterDatas.Clear();
}
why is this method doesnt work?
it doesnt show any error but it wont delete the list
you can format the !code to make it easier to read . . .
๐ 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.
oh yea sorry, here it is https://gdl.space/azerakuvox.cpp
have you considered the method is not called?
you can post small code blocks, just use the formatting like so . . .
static public List<string> characterDatas = new List<string>();
static public void ResetData() {
characterDatas.Clear();
}
it is called i have other code than that, but i make it simplier the problem
how to do that?
can you place a log inside the method and check that it appears from the console?
also, is there another class that adds to the list? it is static, giving any (outside) class access to it . . .
read the bot message: Inline Code . . .
oh yea sorry
the data length supposed to be shorter but it doesnt
all of these logs are inside the ResetData method?
static public void ResetData(){
newFile = true;
isFileReaded = false;
characterNames[0] = null;
characterNames[1] = null;
characterDatas.Clear();
Debug.Log("Data reseted.");
}
no it doesnt, this is the full ResetData method
all of them are worked except the clear function
log the size of the list after Clear . . .
hmm it shows 0 now
where is the log "Data length 85" called? smth is populating the list after you clear it . . .
but it wont show 0 on my other method
IEnumerator SetCharacterData(){
List<string> datas = GetCharacterData();
Debug.Log("Data length " + datas.Count);
for (int i = 0; i < datas.Count; i++){
if(!WhatsAppConverter.IsReady()){
StartCoroutine(WaitForFileReady());
datas.Clear();
break;
}
yield return new WaitForSeconds(3f);
if(datas[i][..1] == "1"){
SetCharacterText(1, datas[i][1..]);
BubbleChat1.SetActive(true);
BubbleChat2.SetActive(false);
} else {
SetCharacterText(2, datas[i][1..]);
BubbleChat1.SetActive(false);
BubbleChat2.SetActive(true);
}
//Debug.Log(datas[i][1..]);
}
}
List<string> GetCharacterData(){
return WhatsAppConverter.characterDatas;
}
it comes from here
i think i know why
this logs the size of the datas list, but you Clear the characterDatas list . . .
is it different?
because i get the datas from characterDatas
yeah, i just saw. i had to look back at the previous snippet. it's the same list. you need to check/search where the list is used because somehwere you're adding to the list . . .
i do the add function to characterDatas, is it matter?
other than that theres no more
yes, Add will add items to the list. if you add items after calling Clear (clearing the list), the list will not be empty . . .
Using the new UI system I'm noticing the following is being called twice.
public void UI_Cancel(InputAction.CallbackContext context) {
//If Pressed
if (context.performed) {
Debug.Log("called twice?");
}
}
I'm kinda confused why this happening as I assumed perform should only happen once no?
Hmm, isn't there something like up and down trigger here ?
This is using the new InputSystem. So no.
but it added to the datas only not the characterDatas
also the Add function is for characterDatas
I mean, performed both concerns up and down iirc, so that would explain why it triggers twice
Nope.
Started = Starting to Press.
Performed = Pressed.
Canceled = Release/Up.
Long time I didn't mess with this so my memory about it is foggy. You may have more luck in #๐ฑ๏ธโinput-system tho'
List<T> is a reference type. the datas and characterDatas variables point to the same list (object in memory). when one changes, it reflects in the other . . .
i think i know a way
wait
oh my
yea i found it why
readonly static List<string> lines = new();
public static void OnSuccess(string fileContent){
string[] fileLines = fileContent.Split(new string[] { "\n" }, StringSplitOptions.None);
lines.Clear();
for(int i = 1; i <= 50; i++){
lines.Add(fileLines[i]);
}
WhatsAppConverter.ReadString(lines);
}
this is the method i use to set characterDatas, its because i dont Clear() this one so it adds other too
@cosmic dagger tysm for the help dude
nice work! 
Hello, is there any way to have these arrows for public int variables? I would like to increment a seed variable 1 by 1 with a button press in the inspector frame
youll have to make an editor script for that
alternatively you can use the Range macro which isnt the same thing but is a slider
create a custom inspector for it . . .
also you can drag the field anyway by default
instead of the arrows, a simple custom inspector would have two actual buttons: one the increments, one that decrements . . .
Yes I currently have a slider but its not really precise
Ok thanks I will take a look
Can someone help me? I have camera and I want to make "cutscene" like for example you click an button and the camera will rotate 90 degrees in an animation how could I do that?
i'm making an inventory system for a 3d unity project. right now i'm trying to add a drag and drop system to the items but it doesn't work.. I only have debug.logs right now and nothing shows up in the console
DragDrop - https://hst.sh/cufazifuva.cpp
ItemSlot - https://hst.sh/movubemodo.csharp
i've read forums talking about adding a StandaloneInputModule to the event system but because im using new InputSystem i need to use a InputSystemUIInputModule. I've added a canvas group to the item, made sure the canvas has a GraphicRaycaster. I also did an Event System debugger - https://hst.sh/musobofono.cpp and still nothing shows up in console. when i click on the item absolutely nothing happens
first off do you have a scene with your button inside? fun fact: you can access the main camera by using Camera.main. you can get the transform from the main camera to rotate it.
Oh thanks for that I didn't know but that doesn't fix my problem since I want an smooth animation do you have some suggestions how to make that?
I think I heard about some animator thing in unity
Also yes I already have my button and everything
Just I need the smooth camera animation
Hey am complete beginner and doesn't understand the c of c# and not even unity what steps should I do to learn all
I would recommend this video try to make the game with the person it helped me the basic a LOT!
https://youtu.be/XtQMytORBmM?si=7T7wYExyOpXA1Y4v
๐ด Get bonus content by supporting Game Makerโs Toolkit - https://gamemakerstoolkit.com/support/ ๐ด
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then gi...
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yea that's also a thing but I prefer videos over an documentations.
Btw I'm Weak in English so probably I doesn't help me a lot I want to learn the ui first and Adding Animations and Scripts And GameObjects things
Cause for the Script thing I don't understand even the c of code
that's not the unity documentation . . .
Unity Learn does have both text and video though
I gotta say that the GMTK video is pretty decent for beginners too
then i recommend learning C# first before diving into unity. you can do both at the same time, but it will be more difficult to grasp (learn) both concepts . . .
I know I know but Im just talking about mine preferences
It's all fine to use learn unity
Dude, I mean I am not comfortable to code with my hands but I can read and understand codes so I use ai and review his codes and customize but if you say I think I need to learn writing โ ๏ธ
I thought I was the only one lol
Hi - firstly please direct me if I should be posting this request for help elsewhere? I have not used the Official Unity Doiscord and cannot seem to find a HELP forum... Here is my dilemma, I have bee trying to post my most recent Jr. Programmer module (debugTheApp) as evidence of completion. It askes me to "Add a link to your WebGL project" However, when I sut-n-paste the link on my unity play page i get a pink pop-up that states "project_unsupported_url" I am unsure what to do. And i cannot complete the module and proceed to the final quiz unless I can paste a viable link. Good Grief. I have searched High & Low for help but to no avail. Please advise and/or redirect. Thank you.
Definitely avoid ai until you know enough to tell when it is lying.
I know how to code and I'm just lazy so I use ai but of cource I edit it and I don't use it for everything
in what way does getting AI to generate bad code and then having to review it line by line to get it to work save you effort?
As I said I use it for simple thing that I'm just lazy to code and I'm sure that ai will know
It works for me
!blender
A supportive community for Blender artists of all levels. Share your work, ask for help, and learn from others! https://discord.com/invite/blender
I just need blender server
Hey, super beginner question here, I've made a movement script that takes RawAxis for horizontal and vertical (top-down game) and I am now making an attack system. My problem is that I need to somehow keep the last inputs of my movement, so if the player has most previously moved up and left at the same time, I need unity to remember that that was the last input and give that direction. How would I do this?
Save the direction as a Vector2 / Vector2Int
private Vector2 _moveDirPrev;
I have it saved as a moveAxis, and whenever I let go of a key, the value placed on the vector2 is gone, how do i keep the value?
A Coroutine should be used in this case
How could a coroutine be used?
You probably set it in every Update, you need to stop at some point
How could I stop it at some point? It's a core movement vector which is multiplied by moveforce to move the player
something like
if(!attacking)
moveAxis = ...;
When the direction is selected, start a Coroutine with this direction as a parameter, which moves the player in specific intervals. Once the direction is changed, the Coroutine has to be reset.
Note that depending on your game, this thing may be better to implement in Update.
How intensive are coroutines? Would I want to be running one every time the player moves?
you can store the previous direction in a separate variable. assign prevDirection = moveAxis before moveAxis to set to 0 when movement stops . . .
No, you should combine it with Update
In terms of ways to run "async-ish" code, it's pretty middle of the road. Not quite as fast as just doing the math in Update, but definitely better than Invokes
Actually, this kind of thing is better to be implemented with Update
Just store the previous direction, and move the player in Update, even if there is no current direction
Ok, so I would record the value a frame before the input is lost?
Once it gets changed, also update the previous direction
Although, it should be called current direction, this way
if (direction != _moveDir && direction != Vector2.zero)
_moveDir = direction;
Move(_moveDir);
Ok, I think I see, so when the direction changes, the previous direction store will change. I can then use this store as a kind of constant when direction is 0
Right
Thank you!
Either check for _moveDir being Vector2.zero in Update or directly in the Move method
Ok, got it yeah
how would I check for each particle in a particle effect the particle death
how stuff like json dont get confused by strings that contain symbols like {}
The syntax encloses strings in double quotes, so anything within a pair of double quotes cannot be confused for language syntax
for the string inside json?
{
"foobar": "{there's no way for this to be parsed as json unless you explicitly do so}"
}
Because they're in strings
Yeah - the JSON parser won't ever treat anything enclosed by a pair of double quotes as anything other than a string
oh right i meant "
If the character is escaped within the string, e.g. \", then it's still considered as part of a string
yes but if i use variable then i cant add \
\\\" would parse as the string \"
You can escape an escape character
Now you're talking about C# string interpolation which has nothing to do with json itself
json doesn't have variables
If your string value already contains " I believe the serializer handles escaping it for you
so json has no way of erroring out from using these symbols
wdym by "erroring out"? Of course it can have an error. Your data is either valid json or not valid json
I mean, it has many ways of erroring out if you mess up your syntax
I suppose it sort of depends on if you're using them properly... Like I could write bad syntax by hand
json, by the way, is by far the simplest popular text based data format there is. It's something like 1000x less complex than YAML and much less complex than XML
yes it can error by hand but it wont error by code right
Depends on how you wrote the code to generate it
code can of course generate invalid json
code can do anything
Garbage in, garbage out
string s = "{ \"badjson\" }";``` I have now written code that generates invalid json
Again, garbage in, garbage out
If you tell it to write bad json, it'll write bad json
for what purpose
Do you want them to be base64?
i want them to not error from any kind of string input
If you're asking if Unity's Json serializer will produce invalid Json with JsonUtility.ToJson, the answer is no, unless there's some bug in their code
be more specific about what you mean by "string input"
Then don't give them bad string inputs
and can it error out if it wont like the string
or erase some symbols in conversion
what string
show an example of what you mean
pretty much that they can have multiple troubling symbols in order
if you mean using JsonUtility.ToJson(someObjectWithAStringField) no it will not cause an error no matter what the data in the string field is
and it wont get erased
JsonUtility.ToJson will add the appropriate escape characters as needed
Honestly you could have checked this faster than this whole back and forth where you don't ever mention what you are trying to accomplish and we need to play detective. Just write code that generates JSON, give it whatever nonsense you want it to, and check if it outputs valid JSON
what does JsonUtility.toJson() do? im a bit uneducated with that side of unity ๐
It serializes a value into a JSON string
it serializes an object to json
It outputs a string containing the JSON representation of the data you give it
As always you can check the docs to answer this kind of question
https://docs.unity3d.com/ScriptReference/JsonUtility.ToJson.html
void IteratingOverParticles()
{
int particleCount = _particleSystem.GetParticles(particles);
for (int i = 0; i < particleCount; i++)
{
float particleTimeLeft = particles[i].remainingLifetime;
if (particleTimeLeft <= 0.2f && particleTimeLeft > 0)
{
SplashBlood(particles[i].position, particles[i].startColor);
particles[i].remainingLifetime = -1;
}
}
}
why does this dont make the particles stop spawning stuff, they keep spawning
for now Im using a quare for the blood just for testing
as you can see its not manny particles and each one has its own trail of squares
this code wouldn't affect the spawning behavior of the particle system at all
it looks to be trying to reduce the lifetime of existing particles
oh I forgot SplashBlood() instantiates a square
is it not working?
yah that makes sense
basically I am just trying to find which ones have already spawned a splash of blood
I thought by making their remaining lifetime smaller than zero and had a check would work
is there any way to make it just die?
in what circumstance
what are you trying to do
alright so Im checking for each particle in a particle system to just when they die or almost die they spawn a gameobject
Ive got all of it done except they dont stop spawning objects even if I make their remaining lifetime less than 0
What kind of object do you want to spawn
another particle?
a gameobject
right now it just has a sprite renderer to it
yes
You should use a particle subemitter instead
it can be set to emit a particle on particle death, or on collision for example
I see, so it isnt viable to creategameobjects from particles
not a good idea in terms of memory/performance, no
and that blood subemitter will remain even after the death of the first emitter?
or do I need to keep it
and just clean the scene when I get outta there
the subemitter is part of the particle system
I see, and can I make the subemitter trigger on particle collision?
I was gonna use something like this
yes but you don't need to write any code for it.
Read the subemitter doc
alright thank you so much! I'll later just use a shader to make it look more like a blood splatter
need your help
when i try is check in changes it tell me changeset has been deleted
waht to do?
#1157336089242112090 for version control help
thanks
subemitor is all I needed and more thank you!
Great, enjoy!
Hello everyone, i have been learning Unity for a couple of weeks on my free time and i just stumbled upon this problem, i never had it before, the thing is i am trying to use those walls as a limit to my player movement instead of just making the user stop at some specific position, for that i created a couple of walls that use a box collider which i thought it was enough but aparently my collision are not working right, anyone knows what could be the issue?
I added some picures so you can see the properties of my gameobjects
Also here is the code i use for moving my character:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyX : MonoBehaviour
{
ย ย public float speed;
ย ย private Rigidbody enemyRb;
ย ย private GameObject playerGoal;
// Start is called before the first frame update
ย ย void Start()
ย ย {
ย ย ย ย enemyRb = GetComponent<Rigidbody>();
ย ย ย ย playerGoal = GameObject.Find("/Goals/Player Goal");
ย ย }
// Update is called once per frame
ย ย void Update()
ย ย {
ย ย ย ย // Set enemy direction towards player goal and move there
ย ย ย ย Vector3 lookDirection = (playerGoal.transform.position - transform.position).normalized;
ย ย ย ย enemyRb.AddForce(lookDirection * speed * Time.deltaTime);
}
private void OnCollisionEnter(Collision other)
ย ย {
ย ย ย ย // If enemy collides with either goal, destroy it
ย ย ย ย if (other.gameObject.name == "Enemy Goal")
ย ย ย ย {
ย ย ย ย ย ย Destroy(gameObject);
ย ย ย ย }
ย ย ย ย else if (other.gameObject.name == "Player Goal")
ย ย ย ย {
ย ย ย ย ย ย Destroy(gameObject);
ย ย ย ย }
}
}
Here is a link to a gif showing what the problem looks like
https://media.giphy.com/media/v1.Y2lkPTc5MGI3NjExbnF0NGt3NTNlaXlnam03cjNpYjIyMmUwOGZtOTQzNmwxbzhxZGlyMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/gGqJM6bzs9XXcbAUnn/giphy.gif
is there any way to find the direction of a rigidbodies movement?
it's velocity is both the speed and direction
assuming you are actually moving it with physics
then use its velocity
!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.
also you should def look into changing this super fragile line of code GameObject.Find("/Goals/Player Goal");
at minimum use tags..
Is it a bad way of looking for gameobjects?
It's very expensive
Do you have any recommendation on which method i should use instead of that one?
The tutorial i am following uses that one so i just used that one
ideally you should connect things in the inspector
If you're following the tutorial, then it's fine, just follow it. But storing a reference is usually much better.
Since it's called on Start once, it's not too bad but
Something to consider
not only that..if the name changes somehow the whole thing breaks
If you wind up using it everywhere you'll find a lot of slowdown
you would still need to change it in the inspector right?
That looks like one of the units from the JPP - I believe it improves upon the approach down the line
Yeah, that's what I expected from a tutorial
if its linked in the inspector the object can be anywhere and have any name , the reference stays the same
Just follow it as they'll probably iterate and explain down the line
neato
burrito
I am following a unity learn course called learn with code
I dont remmeber the name of the instructor
Issue with this implementation is if you have several scenes with a unique goal per scene, you'd have to set the reference per scene
Hi. https://hatebin.com/vbqrpdyplk I am trying a save load system on this inventory. I can save the list with item ids and types. Then I get the items from my database on load. It works fine on the inspector. But the display is not working correct. I am not sure If i should call AddItem or not
Sure you have to do it once, but it's annoying
i then do it via dependency injection
Thank you for your advice guys! Im sure it will be usefull in the future
why is it working for him and not me
print is exactly the same as Debug.Log
doyou have compile errors?
not really the anwser i was looking for
easier
also !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
โข Visual Studio (Installed via Unity Hub)
โข Visual Studio (Installed manually)
โข VS Code
โข JetBrains Rider
โข Other/None
in unity
!code @obsidian shoal
๐ 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.
Did you actually put the script on an object
you cannot use print outside of monobehaiors , also you cannot pass int he context aka the object that called it
still
no it is not
neat idea
thanks
second day using unity and cs
It says it is identical here: https://docs.unity3d.com/ScriptReference/MonoBehaviour-print.html
everyone starts somewhere, and i still suck at it ๐ฅฒ
Junior Programmer course on the !learn site is very useful
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
ohh looks like it
i will give it a try
read again 'The Message is identical'
not identical
here is a simple example if you're curious
https://unity.huh.how/references/simple-dependency-injection
jesus Christ what have i started
first things first you should have a configured IDE
So what are the diferences inside a MonoBehaviour? It's probably calling Debug.Log under the hood
that's exactly what it is doing
no im talking about the debug.log vs print
I'm talking neither buddy ๐
that's why I said they are identical
You can pass a second argument to Debug.Log, but you cannot pass it to print
Debug.Log takes in an optional parameter for which object to highlight in the inspector when you click the log. Print cannot do that
If you don't use the parameter, they are the same
Yes, but somebody suggested replacing Debug.Log with print, and this has no difference
Yes, there's no reason to suggest swapping one for the other
more important OP get their IDE configured first and foremost
it's purely preference unless you're using the context parameter
or you need to Debug.Log outside of MB
there's also never a need to switch from using Debug.Log to print. that's just a ridiculous suggestion
yeah. It's easier to use debug.Log then to keep track of MonoBehaviours
i used to use print just because it was faster to type
Also, Debug.Log works for C# classes unlike Print, which is only available for MonoBehaviour derived scripts . . .
i'm making an inventory system for a 3d unity project. right now i'm trying to add a drag and drop system to the items but it doesn't work.. I only have debug.logs right now and nothing shows up in the console
DragDrop - https://hst.sh/cufazifuva.cpp
ItemSlot - https://hst.sh/movubemodo.csharp
i've read forums talking about adding a StandaloneInputModule to the event system but because im using new InputSystem i need to use a InputSystemUIInputModule. I've added a canvas group to the item, made sure the canvas has a GraphicRaycaster. I also did an Event System debugger - https://hst.sh/musobofono.cpp and still nothing shows up in console. when i click on the item absolutely nothing happens
transform.position = Vector2.MoveTowards(kitty.transform.position,bean.transform.position,1f);
anyone know how to make the "movetowards" function move smoother instead of blocky-esc (constant movement instead of teleporting 1f towards it)
like any tips or tricks or just completely different functions
use time.deltaTime inside
Turn down your maxDistanceDelta... Multiply by deltaTime in order to make it a speed in units/second
ok
THANK YOU SO MUCH
YOU ARE THE BEST MAN IN THE WORLD
I LOVE THIS
๐
it still isn't constant movement for some reason
wait a sec I'm dumb
nvm he's still teleporting
you'd have to show your code
{
time += Time.deltaTime;
if (hungry == 1)
{
foreach (GameObject i in beanArray)
{
if (Vector2.Distance(kitty.transform.position, i.transform.position) < minDist)
{
minDist = Vector2.Distance(kitty.transform.position, i.transform.position);
bean = i;
}
}
Debug.Log(minDist + " " + bean);
hungry = 0;
transform.position = Vector2.MoveTowards(kitty.transform.position,bean.transform.position,1 * time);
minDist = 9999;
}
}```
None of this makes sense to me
Why are you increasing your max distance delta every frame
transform.position = Vector2.MoveTowards(kitty.transform.position,bean.transform.position,1 * time);```
you're moving a completely different object than the one that is used as the start position here
kitty.transform is not the same as transform
Yeah, like, a lot of this makes no sense
also yeah the thing with time makes no sense
tell me you never clicked the example link

even in the example step is never increased
to move the kitty toward the bean in a normal way:
kitty.transform.position = Vector2.MoveTowards(kitty.transform.position, bean.transform.position, Time.deltaTime * speed);```
but isn't 1 a speed
it is there tho
Sure, your speed can be 1
Time.deltaTime * 1
you're doing something totally different though
You're doing 1 * time, which is not the same as 1 * Time.deltaTime
you still need time.deltaTime
Yes but you're multiplying it by the time in seconds since the game started
oh
meaning that you'll move 1 unit after playing for 1 second. After one minute, you're moving 60 units per frame
and so on
and then you're doing time += Time.deltaTime; which is just.... ????????
this is like, making a timer
mb
How would I add a nickname to OnTriggerEnter
Wdym by "add a nickname"?
Like how Private void bans
#define NEW_NAME OnTriggerEnter
I have no idea what this sentence means
private void "bans" name is bans
ok..?
what does that have to do with nicknames
what's a "nickname"? in this context?
private void OnTriggerEnter () how do I add a name to that
Ik but I need to have 2 in my script one with a tag and another without
that doesn't make sense
you can only have one OnTriggerEnter
Why would you need two?
private void OnTriggerEnter (Collider other)
If(other.transform.CompareTag = bannedlol)
Ignore the tag
Use the same method for both
I cant
If tag do thing
If not do other thing
Yes you can
Oh i see let me try
You can't have 2
Why does Unity allow for so much use of magic strings? Seems rather detriemtal to good code practices
How would you expect any programming language to not "Allow for" magic strings?
That's the responsibility of the programmer
I don't think I'm aware of any framework or language which actively discourages magic strings
Literally any language that compares strings by value "allows for magic strings"
why cant I view a public List of Arrays?
I'm not saying the language shouldn't allow for it, suggesting for example get rid of the Tag concept
And break all systems built already relying it?
Nested collections are not serializable by default, you'll need an editor script
Backwards compatibility
Tags are by no means necessary, you can avoid them entirely without losing any functionality. Layers are different, but layers also have helper functions to de-magic them
Then my question becomes why did they put the concept in in the first place
Honestly the tag system isnt even bad. Theres just not a major use for it in most cases
Because Unity was made by like two guys almost thirty years ago
That is a really bad suggestion honestly
Hey does anyone know how I can go from one yarn to the next?
You should see the 40 year old C codebase I work with for a day job... I can't rationally retcon any of the decisions they made ๐ฅฒ
_inventoryUIs is the List of Arrays, whenever I play the game, I get a NullException in these lines, _itemSlot and _gloveInventory are both Arrays of a class called ItemSlot
Okay, and where do you initialize _inventoryUIs
...yarn?
...yarn file?
Yarn Spinneri thnk
Yarnspinner
here
That's where you declare it
the list is null
where do you new it up at?
where do you actually create a list to store there
You may need to throw this question over to that asset's support/community channels
like = new List<...>
yes
yes
where do you do that
Probably best to ask in a server specific to that or the devs
They have a discord
I suggest Ink is much easier than yarnsnippner imo
I have never done that with any list ive created and they worked
if you don't new the list up, the .Add() will try to add to null
because they were probably serialized in the inspector unity does new() for you
Probably because they're serialized and created by the inspector
oh yeah
as I said before, nested collections cannot be serialized
okay, makes sense
So Uhh. I changed some stuff in inventory.
Now I get an error on line 29 on the second link. Null reference exception it says. I cannot understand why.
https://hatebin.com/tufcfyntjf
https://hatebin.com/yosvipddmn
Either image or newItem is null
I want to have all my walls having the same sized texture throughout, but because it's a maze, there are many different lengths and widths for walls. The tiling system makes the texture stretch differently between walls. Is there any way to have them all be the same size throughout the different walls?
- Properly UV-map the wall meshes
- Use a triplanar shader
I should debug to see that right?
yep
btw if you build your walls with ProBuilder instead of scaling cubes it will get UV mapped properly automatically
Thank you.
No?
0.5 or .5 dont work
Floats supports decimals, so the smallest number is one closest to 0 you can get with the size of a float
You need to append f to floats in C#
0.5f
Otherwise, it is considered to be the type Double, which isn't the same.
thank you
How can i make so the DontDestroyOnLoad Objects stay there also when i leave play mode?
You can't, it's a runtime thing.
Ah neat - I never knew there was a constant for that
You should store the data you want inside a file if you want to use for after runtime
a scriptable object might work too ๐ค
I need to put the objects inside of this script, which is in another scene than the object
Cross scene references are not supported.
The Objects would load in with DontDestroyOnLoad, does that work?
no
you won't be able to reference things in the editor if they're in a different scene
are you bringing all the objects in the list with you?
you can open multiple scenes too btw, you just can't reference between those scene objects
It says this on newItem,
Hello I have a bottom menu im using to identify which panel of a screen is in focus, im using 6 dividers that represent 5 gaps (one for each screen), and want to position the dividers equally spaced with the exception that the currently focused panels dividers occupy a larger space. I've been defeated by the maths so a push in the right direction would be greatly appreciated.
private void AdjustDividers()
{
Debug.Log($"{selectedPanelIndex}");
float canvasWidth = viewportWidth;
float indicatorWidth = selectedIndicator.rect.width;
dividers[0].anchoredPosition = new Vector2(-canvasWidth / 2 + dividers[0].rect.width / 2, dividers[0].anchoredPosition.y);
dividers[dividers.Length - 1].anchoredPosition = new Vector2(canvasWidth / 2 - dividers[dividers.Length - 1].rect.width / 2, dividers[dividers.Length - 1].anchoredPosition.y);
float availableWidth = canvasWidth - (dividers[0].rect.width + dividers[dividers.Length - 1].rect.width);
float baseSpacing = availableWidth / (dividers.Length - 2); // -2 because we are distributing space among gaps excluding the first and last dividers
// Position the middle dividers equally spaced
for (int i = 1; i < dividers.Length - 1; i++)
{
RectTransform divider = dividers[i];
float xPos = -canvasWidth / 2 + dividers[0].rect.width + (i - 1) * baseSpacing + divider.rect.width / 2;
divider.anchoredPosition = new Vector2(xPos, divider.anchoredPosition.y);
}
if (selectedPanelIndex >= 1 && selectedPanelIndex <= dividers.Length - 3)
{
dividers[selectedPanelIndex].anchoredPosition += new Vector2(-indicatorWidth / 2, 0);
dividers[selectedPanelIndex + 1].anchoredPosition += new Vector2(indicatorWidth / 2, 0);
}
}
ok and the other thing..?
not the sprite
the UI Image
image
I do not understand why it throws me objet not set to instance
image is probably null
That's why I'm asking you to check it
Do you mean check here?
hello, do you guys have any ideea why is the code giving me the object referince not set to an instance or object?
The error message contains a line number and filename
look at the indicated line
The breakpoint does not work while debugging. I mean does not stop at the image variable.
and which line is 28
How about you just log them
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName(); this one
right here it's stopped in the appropriate place
all you have to do is mouse over image (off screen to the left)
interaction_text is null most likely
ahh I went to the declaration T_T
Either interaction_text is null, or selectionTransform doesn't have an InteractableObject component on it
My guess is you actually have a TMP_Text, not a Text.
BTW there's no good reason to have two separate variables
oh ok i will change it, thx
This
You might enable the debugger's "break on error" function and let it run in order to find the specific instance/iteration which is responsible for the error
Could it be something to do with my InventoryManager? I can send the code link again
NullReferenceExceptions are always the same
there is a null reference being accessed on the line indicated
log all the references on that line
see which one is null
public void InitializeItem(Item newItem){
item = newItem;
image.sprite = newItem.image;
Debug.Log(image.sprite);
}
It says checkmark here. I think it is not null
You'll need to log before the error otherwise you'll never get your log
Log image and newItem
it works now, thx
i had a TMP_Text
To improve your code delete:
public GameObject interaction_Info_UI;
TMP_Text interaction_text;```
Just put:
```cs
public TMP_Text interaction_text;``` Then assign that directly in the inspector. Then also delete the entire Start() function
much simpler, and doesn't let you mess up the types.
i just change in unity the TMP text with normal text and it works fine
ok, i will do it
public void InitializeItem(Item newItem){
Debug.Log($" New Item is {newItem}");
Debug.Log($"Image is {image}");
item = newItem;
image.sprite = newItem.image;
}
Its like this now
or at least i will try
Okay, so at some point you are calling InitializeItem with a null item
And you're passing it a null somewhere
https://hatebin.com/qyttaoamnk I am calling it here line 92
So at some point Container[x].item is null
When I call AddItem on button click. I see that they get added to the Container. When I load the data I also see the container gets loaded thoguh
More Debug.Logs can identify this issue
public void LoadData(GameData data)
{
Debug.Log("Loaded");
Container = data.items;
for (int i = 0; i < data.items.Count; i++)
{
//I can get the data set here without a problem.
Container[i].item = database.GetItem[Container[i].Id];
for (int x = 0; x < Container.Count; x++)
{
Debug.Log($"Container has {Container[x].item} these");
AddItem(Container[x].item);
}
//TODO I just need to find a way to SpawnItems. Items that I get from the Database after loading.
}
}
The last log before AddItem prints nothing
How about this:
var item = Container[x].item;
if (item == null) {
Debug.Log($"Item at {x} was null");
}```
how can i detect when a specific script was added (or rather it's gameobject was instantiated) in the whole game, not just single gameobject
Put an Awake function on the script
okayy, thanks
This is the output
there you go - the item field of whatever is in Container[1] is null
So the first item gets loaded correctly because its Container[0], Second does not get loaded cos its [1] and null
yes because data.items[1].item is null
Hm weird though. I can see them getting added and loaded in the inspector.
If you have (or might possibly accidentally have) multiple InventoryManager instances, you may want to chuck a gameObject into the context argument of the Debug.Log() call, just to make sure that the component you are looking at in the inspector is the one which is responsible for the error
Seems to me:
Container[i].item = database.GetItem[Container[i].Id];
for (int x = 0; x < Container.Count; x++)
{
Debug.Log($"Container has {Container[x].item} these");
AddItem(Container[x].item);
}```
You'[re accessing the items before tyhey're populated
that second loop is looking ahead
before the itemsa re assigned
Well. I am clearing the Container onapplicationquit too
How can I make it so that It populates the Container before spawning the items
uhh so i've got "Object reference not set to an instance of an object"
private void Awake() {
ObjectivesController.instance.addObjective(this);
}
just do one first, then the other
Why is the second loop inside the first?
ObjectivesController.instance is null
I have no idea. I will try it
yh ik
As a rule of thumb, You shouldn't be accessing another object's fields in Awake
initialize yourself in Awake
Do stuff that depends on other things being initialized in Start
otherwise you get a possible order of operations error
e.g. this is running before the Awake on ObjectivesController
so this?
private void Start() {
ObjectivesController.instance.addObjective(this);
}
yes
okay it works, thanks
I do not get an error now. But it fills all 4 slots now instead of how many Items I had on save ๐
Yeah like for example I have item 1 and item 2 in my slot. I save and expect Item 1 and Item 2 on my first 2 slot on load. It loads the first two. Then puts them again respectively filling all my slots
Where is this Muse Animator ? How do I enable/find it
How would I go about checking if a specific transforms rotation is inbetween a set of constraints and do something based on that? This is about as far as I got
I'm more asking how I would define the constraint if that makes sense
That X value isn't what you think it is
Is it not the arrows x rotation value?
Quaternions are 4D Normalized Complex Vectors
It's one component of that value
Unless you have a PhD in math it probably means absolutely nothing to you
This does indeed mean very little ๐
If you want the rotation in degrees in 3D space, that's transform.eulerAngles
don't say that, you know what he is trying to do and you know that wont work
I assume doing myVector3.x would give the x direction not rotation?
you cannot read a quaternion as euler angles, constrain them and set them back.
you need to maintain your own Vector3 rotation angles, constrain them and set them to the quaternion
Do you know of any visual examples? They tend to make a bit more sense to me ๐
no, but what I said is not complex
Telling me it isn't complex isn't all that helpful if It still doesn't make sense to begin with, but thank you for the base. I'll try and do some digging and see what I can throw together ๐
well, what doesn't make sense?
Transform myNewTransform = transform.position;
myNewTransform.x = 10f;
transform.position = myNewTransform;
this is rotation we are talking about
same diff.. vector3 an all
It would give the degrees about the X axis the object is rotated around
or use some of the euler functions.
Vector3 rotation = Vector3.zero;
...
Update() {
rotation.x += 10;
rotation.x = Mathf.Clamp(rotation.x,-90, 90);
transform.rotatation = Quaternion.Euler(rotation);
@quick fractal
Vector3 currentRotation = transform.eulerAngles;
currentRotation.x = newXAngle;
transform.eulerAngles = currentRotation;```
Two main things I'd imagine, specifically defining what the angle is. If I explained the general concept a bit more It might help;
I'm trying to make an arrow rain type skill for a VR game, it would trigger by shooting up into the air between say, 30 & -30 degrees in the air it would trigger. Defining the 30 to -30 limit and comparing the current arrows rotation is the bit I'm pretty confused about.
Sorry if the skill is kind of redundant info ๐
Mathf.Clamp 
Hope im not spamming and being annoying. But I cannot figure why It duplicates my Items in my slot on load? https://hatebin.com/hnydooswgj
Absolutely not
lloll.. i'd just use one of the many rotation methods unity already has..
I mean it does not duplicate the items in slot. I have 4 slots. I save 2 items. I want to load the two items. It loads two then loads them again on the remaining two slots.