#💻┃code-beginner
1 messages · Page 507 of 1
Well there arre certainly people in the comments with the same issue
Timestamp? This is a very long video, where does that code get added?
8:15
https://hatebin.com/dmzabzodzs apparently line 53 is causing this
im very concerned by the angry face at the end of the error
I don't see anything that looks like this code there
What is this
oh wait i see at 8:36 it shows
ChangeColor calls FloodFill calls ChageColor ad infinitem
Line 53 is not at fault. The problem is you have an infinite recursion
yeah but it should stop when all were filled no? unless i fucked something up
that is this code? https://paste.ofcode.org/asapE9CLFUmvQj7at9FDQQ
i guess you fucked up
Does... does that compile
somehow yeah
the correct way to write that is <= (less than or equal to)
but i changed it to != now
Where in the tutorial does it enter that code
yeah idk wth i was thinking with my !>
that doesnt look right even to my eyes
you mean put it in the game itself?
basically you used this operator:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving
So you just had > where mineCount was allowed to be null
which it can't ever be null anyway because it's an int
As far as I can tell, this is the last time it's shown in the video, in the linked video in the description about just this script
It doesn't call SetDestination on it
@rancid tinsel And please learn to cache your GetComponents
in short - the tutorial is poorly made!
jup
Yeah it's not a tutorial it's more of a rambling devlog
but my ai works now!
i know how to i just got GetComponents-creeped, didnt think it would be that much code lol
Seriously?
if (block.GetComponent<BlockScript>().mine == false)
{
block.GetComponent<BlockScript>().ChangeColour();
}
yeah just laziness
bad habit to get into, break it asap
youre right
ill tidy it up right after i fix the bug
to double check by caching you mean making an instance and then changing that instance?
so this kind of thing?
no, just calling GetComponent once (if you must) and save a reference then use that reference
yes
Also look at how many times you are doing the same Mathf.Abs, you only need to do it once for each axis
How can I make a line cast 2D hit every layer except for one? I know there is a layer mask included, but doesn’t that make it so it only hits objects on that layer?
Use the layer mask
in the dropdown you can select all the layers except the one you want to exclude
public LayerMask mask;``` you can configure it in the inspector
Ooh thanks!
I am using GetComponentsInChildren. is there a way to limit the hierarchy levels? i mean, i only want the immediate children, not all the levels
best use a GetComponent inside a foreach on Transform
Ok, i will look into that, thanks
How would i make this work so that it uses the prefab I've slotted into here. Whenever the code on the script is run It hits me with the "The Object you want to instantiate is null"
script isnt on an object until runtime
The default values will only apply to new instances of this script added in Edit mode. It won't affect anything already in the scene, or instances of this script created at runtime
any reccomendation on how I would do this then? The way i've been doing it wont work since ths cript isnt on anyhthing until runtime
You'll need to get the reference after the object exists. Either pass it in from another object that's in the scene before play mode starts, or load the prefab from Resources
move the prefab to a Resources folder then use Resources.Load in the Awake of the script
Hey, I'm having an issue with speed (not the drug). I have ```cs
public float speed = 15.0f;
are you changing it in game? if so unity does not save changes that way
changing it in your code likely, elsewhere
or you're looking at the wrong inspector
or changing it in Play mode
it updates the next frame
not after pressing play/pause
then most likely what Praetor said
I have a bit that sets it to 0 at some points but that bit of code isnt being run during the issue
Show !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.
Okay, so it's only changing in an OnCollisionEnter function on this script, but it's public. Try changing it to [SerializeField] private float speed = 15f; and see if you get any errors.
(please forgive the horrible code)
That would mean a different script is changing it
also are you manually changing the rigidbodies transform?
yep found what I think is the issue
yep got it
I have a World Object with a world script where I instantiate the player and have ```cs
public float _playerSpeed = 15.0f;
if (gameRunning == true)
{
player_script.speed = _playerSpeed;
}```
I wrote it a while ago. I know you can do it other better ways now
If i were to try and delete a clone of a gameobject, how would i make sure it only destroys the clone and not the prefab?
The game wont let you destroy prefabs (assets) anyways. Itll give you a warning/error if using Destroy
yeah but it still gives an nre
Then you have a NRE issue which is entirely different from what you initially asked
It depends, either
by checking if the object is null and doing whatever appropriate logic after
Or just assign the reference and move on.
would you like my script rq
🤷♂️ if you need specific help with something in the script then sure show it
I'm not sure anything would really change about what I said above though.
im just not so sure about the null logic
you would look at the line the error is occurring on, find out what thing is null, and then either make it not be null or stop trying to do stuff to it
ive taken a hiatus from unity so im a little rusty
For example if you have a null error because something from inspector isnt assigned, and it realllly should be assigned, then follow the 2nd statement I wrote above about just assign it and move on.
hold up
what if instead of Destroy(this.gameObject), i do:
Destroy (clone.Object)
i named the object clone btw
Similar to this:
clone.velocity = transform.TransformDirection(Vector3(0,0, speed));
Destroy (clone.gameObject, 3);```
anyone have a quick way to pick between two numbers that arent sequentially next to each other? i wanna pick between indice 12 and 14 but obviously i cant just use Random.Range cuz itll include 13 as well
do random.range, check if its 13, if it is +1 or -1
all g
That will pick one of them twice as often
12 + Random.Range(0, 2) * 2
Random.value > 0.5 ? 12 : 14
at least i tried my darndest
yea !!
ye
i have fixed the nre
yet, another issue rises
now when i create this object it has no force behind it even though i scripted it to.
{
GameObject NewShot = Instantiate(Shot, BowFirePos.transform.position, Player.transform.rotation);
ShotPhys.velocity = transform.TransformDirection(Vector3.forward * 25 * Time.deltaTime);
Destroy(NewShot.gameObject, 5);
yield return new WaitForSecondsRealtime(8);
}```
P.S i have tried putting the velocity line in the update as well and nothing changed
(ShotPhys is the Rigidbody of Shot, Shot is a GameObject.)
Also just tried changing the line to
Shot.GetComponent<Rigidbody>().velocity = transform.TransformDirection(Vector3.forward * 25 * Time.deltaTime);
hold up, got an idea
yeap
fixed it, sorry for filling up chat
What is ShotPhys
What's the difference between Vector3.magnitude and Vector3.distance
i mean taking two vector3s and calculating the magnitude difference
adding them and subtracting the smaller one doesnt sound wrong to me
however,
i do not do magnitude and difference calculations
The same difference between x and x - y
Distance requires two points. Magnitude is just one point.
oo okay
ah gotcha
why are you pinging me
I have no idea what you are saying
I'm trying to make an enemy AI that jumps if there is an object between it and the player. To do this, i am using a line cast to check if the line is broken before it reaches the player. Unfortunatley, it does not work right now, and im not sure why. If someone could explain the issue, that would be great! https://paste.ofcode.org/F2U3r6TtfGfRUqxPMXdpFx
Linecast takes two points. You're giving it a direction and a point.
https://docs.unity3d.com/ScriptReference/Physics.Linecast.html
The first major issue here is that you're trying to mix up Transform.Translate motion with Rigidbody motion.
You need to pick one and stick to it.
I had it as rigidbody movment, i just changed it to see how it would work
The linecast logic is also definitely off. Partially what digi said and partially just - it doesn't make much sense at all
what's with (player.position.x * 3)
I think the direction vector should be two vectors added together to decide which way it shoudl move if that makes a difference
Also this code:
Vector2 Stop = new Vector2(0,0);
rb.AddForce(Stop);```
does absolutely nothing
adding zero force is just that
doing nothing
A direction is not a location
"Hey man what's your address?"
"West"
Fair point
To make the difference between the enemy and the direction it's supposed to be further apart. I was using it for testing earlier but it ended up not being needed
Yeah i learned about line casts today so im pretty new to this
That's multiplying the player's X position by 3. So, for example, if the player is at (100, 0), it would give you (300, 0)
Yeah, i was trying to make it so the linecast went towards the player but looking at it now that seems redundant huh
Yeah i see that now for sure
does any one understand why i cant drag and drop my sprites into my animation tab???? Beginner btw
- not a code question. #🏃┃animation
- you need to select the object you want to animate and you probably need to also add the sprite property to control it
sorry didnt know exactly where to post this
what toggle
do you meet any requirements that are there to be able to click the toggle?
idk what your trying to click so its hard to help
ah i see, do you have a EventSystem in your scene?
is something blocking the button perhaps?
no idont think so
Are you trying it in play mode or not play mode.
in play mode
I am not understanding what are you trying to do and what is not happening.
the toggler aint toggling
hi! i have an issue where i can't set the .cull of CanvasRenderer's using booleans! it works when i do !textRenderer.cull to flip it but refuses to take bool input
What do you mean by "it refuses to take bool input"
Can you show your exact code and the error(s) you're getting?>
its not throwing errors unfortunately
these functions are being called through unity's event system fyi
Add some Debug,Log, but there's no reason that wouldn';t work
you're probably passing in the wrong value (true or false)
or something like that
also when adding either of them to my awake or start functions, things are weird ~ only one of the canvasRenderer's has anything happen
There is a script attached to your toggle did you wrote anything not to toggle in update method.
no
i have tried this! the loop is working just fine
(and i have passed true and false via a checkbox in the unity inspector)
Debug.Log the value parameter as well
... value?
where is the value param? /gq
(meaning the active boolean? that seemed to be working fine)
Did you tried dynamic bool option.
im finding the new input system difficult to work with, should i go back to the old input system?
what is the dynamic bool option? and no~ definetely not
(new) input system isn't a requirement and for smaller projects I wouldn't suggest putting too much time into it
It was not you I was saying it to toggle problem.
ok!
Show where you are calling this
!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.
I keep getting this error and I can't figure out why
error CS0246: The type or namespace name 'boxCollider2D' could not be found (are you missing a using directive or an assembly reference?)
I thought that I referenced boxCollider2D in the first few lines my code
in your OnTriggerEnter
your trying to check a boxCollider2D
as a type
but a. that doesnt exist
b. im not sure if you can use something other than the one premade with OnTriggerEnter
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnTriggerEnter2D.html see how the docs do it
I think maybe I dont understand the OnTriggerEnter
now i get this error
(27,32): error CS1061: 'Collider' does not contain a definition for 'boxColider2D' and no accessible extension method 'boxColider2D' accepting a first argument of type 'Collider' could be found (are you missing a using directive or an assembly reference?)
Check the docs. Does the Collider class have any variables or functions named boxColider2D?
https://docs.unity3d.com/ScriptReference/Collider.html
its not even running, but if hasDone = false it should be running that first if statement on awake?
Show the inspector of this object
Using the method input.GetButtonDown("Fire3") is called under two different buttons between my laptop (mac) and PC(windows). Is there any specific cause for this? Movement is also different between the two, assumendly because its placed under void update and not fixed update
inspector takes priority, has to be false there too
Whenever this object is first activated, it will run the first part of the if condition.
Is this object active in the scene?
Check the Input Manager for what it is mapped to.
https://docs.unity3d.com/Manual/class-InputManager.html
to explain, it is a warning screen that I only want to show once, when you die in the game the scene is reset and I was trying to find a way to not show the loading screen after dying again
so my thought process was to setActive on awake
So how do you intend to maintain this data between scenes
Yeah they’re both mapped to joystick button 2 (I’m using controller for this), but they’re two different controllers
you are right this totally makes no sense Awake does not save that when reloading a scene
do you have any idea a work around for this or do i need to rework how i reset scenes?
You will need something that persists between scenes, either a static variable or a DontDestroyOnLoad object
ive made this melee attack and implemented a script that allows it to play on a button press, which works. the issue is it only works once, i cant make an attack after the first time i do so, i dont think its a scripting error i think its an animation one but im unsure
got it, thank you!
Thank you for helping solve the OnTriggerEnter issue
but I was trying to solve this issue so that this code would stop the gameobject it's attatched to if it hits an object with the tag "player"
You have a function in your function
you also might wanna use OnTriggerStay/OnTriggerExit to detect the colliding for false
both void run and void OnTriggerEnter are the functions your talking about right?
Your function is inside of another function
void run? do you mean update?
Which means Unity won't call it
How do initiate download from game made with unity ? For example, in android web browser initiate a download and the file is saved in download folder, i want to do the same with my game
write the data to a file with https://learn.microsoft.com/en-us/dotnet/api/system.io.file.writeallbytes?view=net-8.0
And how do i get the path to download folder ?
yes you can put whatever file path you want
And it will be saved in download folder regardless of what the filepath is ?
But what if i want to allow the download to be managed by external download manager instead ?
what does "external download manager" mean
Sounds like you're asking an Android specific question?
I.e. this?
https://stackoverflow.com/a/9033224
You would need to use native android Java code for that
It is that, when i have a download manager, instead of my browser downloading the file, it will be intercepted and handled by download manager instead
i want my download to be handled by download manager as well
How about other than android? Is it possible ?
Every platform will have its own special way
so it depends on the platform
Ah okay, thanks
So no built in way in unity to do it and i must use platform specific way right ?
yes
Okay thanks
hi! sorry for the late response: its through a UnityEvent handled in a silly way: its added to a player's unityevent and the way that gets invoked is on keypress through unity's input system
Show a screenshot of the event
How do i check if assetbundle is a scene without loading it ? for security reason I want to allow loading assetbundle except those that contain scene
The reason is because scene can contain script placement in object which is dangerous
hi, im currently having a trouble with MissingReferenceException when reloading domain, is this chat where i ask for help? and if it is, anyone found the solution to this issue?
no im a beginner unity user, here's the full topic link that i post on Unity website of what happened to my problem!
the variables are still assigned during runtime
Disabling reload domain means that when running the game, several things happens, including that no static variable will be cleared nor assigned
Easy way to check if that's the culprit is try trigger a recompilation, by modifying your code somewhere or something alike, and then look if the first time runs correctly
i have only 1 function using static but i use the method on unity so it work when not reload domain
is it the right way to solve static issue when disable reload domain?
The right way to solve it is to enable domain reload
I think that he might've disabled it for the same reason as mine- Waiting time
that's true but man it took ages to reload everytime ToT
It's annoying to wait for reload whenever I run it
These kinds of issues are inevitable with it so you'll have to choose
It's not exactly inevitable
questions: will disable reload domain cause effect on instantiate prefabs?
I made complex systems with it disabled, you just have to be careful with what you do, and understand what gets executed only upon recompilation and what does not
Nope?
damn i have no clue
I think that runtimeInitializeOnLoad might only execute once across multiple plays though
Probably is the case
Basically that function will only be ran when you trigger a recompilation or so
It's hard to track down exactly what happened, though, without testing a bunch of things or walking through with a debugger
so when i start, it initialize this function once, to reset all data, the initialize works fine, but when i start invoke the function again during the playtest, the issue occur
Looks like this is per inventory slot?
yea it is
Welll... Awake, Start, Update calls would still happen perfectly normally on monobehaviours, no matter domain reload or not
ok i triple checked everything, and im like 99% sure the issue was in this static
is there anyway to disable domain, but still able to run this static normally?
Hmmmm... Lemme think...
I'm pretty sure that the attribute on the method only runs on domain reload...
new InventoryItem looks like it could totally be a constructor
Personally. I'd say that you might as well make it:
public static InventoryItem empty = new InventoryItem(null, 0) or new InventoryItem(), if you don't need to assign anything
referenced by InventoryItem.empty
the full struct of the inventory item
Quantity is 0 by default, and item is null be default, normally, so you can drop the item = null and quantity = 0
Not sure how the IsEmpty'd run tbh, I gotta test some things
public struct Itemstack
{
public Sprite icon;
public int amount;
public static Itemstack empty = new Itemstack();
public static Itemstack empty2 = new Itemstack(){ icon = null, amount = 1 };
}
This runs just fine
it said that the parentless struct constructor isnt avalable in C# 9.0 ...
Yeah, that's the problem, but then again, it doesn't look like you need to run a constructor either, do you?
Cus references are null be default, and any number variable are 0 be default
hmm thats fair
so i should follow this and applied to my code?
Also, yeah, lacking support for parameterless constructors is a big pain in my neck at times, as sometimes I'd like to just follow normal conventions but make sure that some initialization is always done, but then that comes in xD
Sure, the first one should already do the trick
As long as you don't modify it, which I doubt you will
Const in C# is a hassle too for me '^^
but i though that it still have static in the line? :\
Even though it makes sense for it to be a const
Yes, the thing with static is that the value within won't be affected by scene transition, replaying the game and so on
Well, honestly you'd best test and read about it, I'm no expert, I just dealt with it quite a lot since I hardly ever keep domain reloading on
Essentially only domain reload will assign the function's initial value again, so without it, it wouldn't revert to null/whatever the default value is upon pressing play
However, domain reload or not, the static variable will never automatically revert to it's initial value upon transitioning scenes, it's important to keep that in mind
ok it still didnt work, thanks for your help though, maybe i will try to ask someone for a full check because im not capable of doing this XD
Mistake on my part: RuntimeInitializeOnLoad is an attribute that causes a method to execute whenever you start playing
Imma just dig into this a bit more myself, since I figured that I don't know this static stuff well enough, bye
No problem
What was the initial issue again?
DomainReloading caused a NullReferenceException to be thrown
Sounds like a typical static variable issue in my opinion
on what line was the issue?
Line 31, Ev's the one asking, though
https://discussions.unity.com/t/dissable-reload-domain-on-play-mode-cause-missing-reference-exception/1534389
Phew, is the code somewhere readable? 😄 @tame valley
That line references an image... Uh, actually, this issue doesn't make much sense now that I think about it, it's likely something assigned in the inspector?
if you interested in helping, i could give you my current scripts, its not long, but idk how to upload all of it for you to check? ToT
!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.
Well, anyway, Imma be off then, cya guys
when the error occurs, what is the serializedfield looking like? is itemImage actually empty in the inspector?
i checked, the inspector still have all variables assigned
Of the created object in the scene hierarchy?
heres the picture, im pretty sure that its from hierarchy
Pretty sure? You should check right now 😄 run the app and see when the errors occur, click on the error, it might highlight the object its crying about or you just debug log the gameobject before you enable the itemImage, so you know its name
the first time i ran after reload domain, it works as intented, but the second time when i dont reload the domain, the issues occur
ok im checking the error log now
i paste the full error log here
https://discussions.unity.com/t/dissable-reload-domain-on-play-mode-cause-missing-reference-exception/1534389
ived checked everything
so you are reloading the domain, then start playmode?
ive do all the debug.log
and after that, you are just starting playmode without reloading?
one thing I notice, you never seem to unsubscribe from your events
so when i save my file from editing, the domain automatically reloaded, so i get the first run successfully, but in project settings i set reload domain to be disabled , for faster play, and the error appears
Id say, you are creating objects on the first playmode and when exiting, they get destroyed, but as you do not reload anything, it will just keep the created objects and try to access them, which turned null on exiting playmode.
is there a proper way to unsubribe events when i quit the game.
ondisable usually
yes, OnDestroy or OnDisable
you could also double check your created lists count. I guess, it adds up on the second play run when not reloading
the 2nd time i run. ItemList still have the same count which is 33
When the error is happening, what is calling the ResetData method?
Oh wait,you are calling it in awake?
Awake was when i first launched, all the item slots are create and reset to the empty state
believe it or not, the resetData actually work the first time when it run, and after that when i invoke the ResetData function again, it crashed
do you want the full project im currently doing for a deep test, if you got time?
Nah sorry, got my own hassle with visionos here 😄
yea fair enough
but you are subscribing the oninventoryupdated function, which is the start of the whole script execution. And never remove the event subscription. I would remove the image.enabled line and debug.log the gameobject, maybe give it a unique name if image == null and check again in the project hierarchy.
ok lemme go through and do all the unsubcribe thing.
MissingReferenceException: The object of type ‘Image’ has been destroyed but you are still trying to access it.
you are trying to access it somewhere in your code, after destroying it
which points to not unsubscribed events more often than not
I am just wondering, why its calling the image to be destroyed but not the whole UI_Item holding it and therefore firing a null error upfront
OHMYGOD IT WORKED
i unsubcribe everything. it worked
thanks so much @languid spire @astral falcon
welcome to delegates, events and other subscription fun 😄
Always, always, always unsubscribe. Lesson learned I hope
LESSON LEARNED
We all been running into this at some point 😄
ARUGHGHGHGHGHGH
i swear this took me like 8-9 hours to debug this crap
once again, thanks so much, im so happy rn
How do i mark folder/file as being used ?(for example, if user try to delete a file that is being used by app, windows will throw error that it cant delete the file because it is being used)
Depends how you open the file, but generally you should open it with a using statement so that it's automatically closed when you're done with it
can i prevent folder from being modified while my app is running ? (inserting new file/deleting file is not allowed, rename not allowed, etc)
google for "lock folder c# windows"
Ok thanks
Not sure what I'm missing here. The script has no compile errors and it looks like the name is the same as the class name.
do you have any compile errors? even ones you think are unrelated to this component?
Not that I have seen. Or at least non showing on the console. I just fixed a bunch of them.
looks like its just messages saying the referenced script is missing
clear the console and see if any appear
then change something in the code, save, and make it recompile then try adding the component again
still nothing
screenshot your entire console window
only the 2 things in it atm
at the very least you should fix those warnings. if the issue persists then try restarting the editor
werd. I didn't think those would keep me from attaching a script so I thought I'd try.
Had similar issue, turned out to be just some old duplicated script with different class name but the same filename or something. Don't remember for sure, but I'd suggest double checking for duplicates
will do. Thanks for the input.
If I wanted to do a seeded run in my game. Whats the proper way to handle it? The way I was handling it before, seems to be wrong at this point.
My General Thought is: Everytime I do an action. EG: Open a chest, Spawn in something "Random" or Load a random level I need to store the seedstate.
However, if a player say, skips opening that chest. Because of how I have it coded right now, not opening that chest will force the next room to be different, because opening that chest effects the seeded state.
Just wondering if theres another way to go about this before I start digging into running the random generation when the chest spawns instead etc.
use the seed to make those decisions without the player being required to interact with the objects to do so
Hello
I got this error "NullReferenceException: SerializedObject of SerializedProperty has been Disposed." after the exit play mode.
I suspect it's because prefabs that was referenced destroyed after exitting play mode? usually how do you solve these types of problems, does it leans more to the code structures?
please use a bin site if you are going to share a large stack trace 👇 !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.
but if you have not written any custom editor code and you don't have any assets that have any custom editor code then it's probably just a random unity error that you can probably clear and ignore
Instead of doing:
- Whenever the chest is open get random value.
do - Whenever the chest is initialize get random value. (Be sure that the initialization is deterministic though. Do not rely on Awake/Start)
should i use deltaTime or is it fine like this?
Don't use deltatime here
The default forcemode (Force) already multiplies the force by fixedDeltaTime
alright thanks :D
Isnt it that a force is not a timed unit (like speed would be)? It doesnt matter if you apply a force this or next frame the resulting speed will be the same 😄
about 2 weeks ago i last opened my project and it had no errors and everything was working fine and now i opened it and all of a sudden i got 12 errors and that required me to go into safe mode i went into safe mode and i dont understand whats the problem can someone help me?
Sure, if you post the error messages
something wrong with the pacakge, have you relaunched Unity ?
(this isn't a code issue, for this channel)
if that doesnt help close unity, remove the library folder, open project (⚠️ takes very long depending on project size)
my bad
ForceMode.Force and .Acceleration do use deltaTime, the * dt part here:
So you'd use those for continuous forces and the other two modes for instant forces
Never use deltaTime with AddForce.
by u saying remove the library folder do i js delete it?
yes, just close Unity first
Yes, close your project, delete the Library folder in your project root and open your project
that will trigger a full reimport
Hi all, I'm working throug hthe beginner tutorial on unity learn and they asked me to make a "MonoBehaviour Script" but I'm not seeing the option anywhere
C# Script
The tutorial is most likely done on an older version which has different naming
it's always been C# Script
what is this channel
What do you think the words "code" and "beginner" mean?
Right. If you're here to act goofy, you will be removed.
Ask questions and discuss anything related to beginner coding concepts in Unity
ok
yes !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.
Wait, the code is very long
then use one of the top links
how?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Like this i guess?
Click the link. Copy and paste your code into the site. Press the save button on the site. Copy the url and paste it here.
Wait, thats the weapon script, i shouldve given the camera script
Does anyone have a good recommendation for a YouTube series to learn C# in unity?
Brackeys, not perfect but good for beginners
otherwise !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
That's the correct script now
Thanks!
I've spent hour and hour just wanting to fix this, still failed :(
if you have spent so long why does your code show no indication of debugging whatsoever?
I deleted again
why?
It's just annoying for my eyes :,)
bye
is there a way to make it so that when I open microsoft visual studio from Unity, it is automatically setup for c# (shortcuts and autofills, etc)?
Yes, if you follow the !ide instructions
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
• :question: Other/None
sure !ide
thank you!!
It's always recommended to leave debug? i though people dont like it? im still beginner
You can remove it before you release something. Leaving it in during development is fine?
Also who are "people"? Are you working in a large team that these "people" are not liking your debugs?
Im solo
So i dont really know other perspective, sorry
But thanks though, now i know majority recommend to make debug log stay
it makes no difference to the end user, it all depends on what you want to do
I tend to tidy up logs when I no longer need them so they don't get in the way with other development
I see i see, i'll note that tips :)
why does the highlighting not work half the time, it's getting kinda annoying
dont they slow the game down, and their text goes into the game folder somewhere? or did they fix that
they make a difference to performance, when there's thousands of them being spat out every frame
debug.log does not output to anywhere afaik, or that I've ever heard/ seen
There's the player log, but it gets wiped every time you start the program and if you're logging so much that filesize becomes a problem for plain text, stop
Highlighting what? Can you be more specific
like..everything?
if you first opened it, did you wait long enough for it to update?
VS is kinda slow
Yeah that's true I also wait like a minute for to load the whole VS
yeah thats pretty normal ime. Depends on the PC sometimes VSC loads faster but its tricky to setup at first
It's just that this software is a very heavy thing so sometimes it takes longer than usual to load the extension (I mean that highlighting names algorithm)
its not called Highlight names algorithm, what you're referring to is Intellisense
Yeah I still don't know alot of VS settings i just know the basics setting like font size or extensions
I thought intellisence is a thing that helps in completing a word before you even wrote it fully
And gives similar methods on the name you writing
I mean Similar in name
yes it also does suggest things
Yeah really helpful thing
um also is there a way to make visual studio not open every time I create or delete a script
Do you guys know a way for menus not to stack over each other when activated, I can disable and able it but when I enable one and enable another again it just stacks over the previous and the former one don't disable
ah okay
I mean the highlighting works when I open it but sometimes I come back to it and it doesn't for some reason
and the auto complete stops working
Hello people can anyone tell me
how do i make unity webgl game landscape by default
The size and shape of the WebGL canvas is determined by the HTML/CSS on your actual webpage
it's not something that would be controlled in Unity
Basically i have a desktop game on webGl now I want it to run on the Mobile browser also so I wanted to rotate it when the game loads
So basically i should just add rotation property?
I don't know anything about website design tbh
Okay I'll try to do it by css first
anyone got youtube series to help me learn C# coding in unity?
Better than YouTube: https://dotnet.microsoft.com/en-us/learn/csharp
well I guess it links to a YouTube playlist anyway lol
you can just do Up = Input.GetKey... instead of using IF statements
hey guys i have some trouble getting the debugger to work,
first of all the attach to unity option does not appear in the left debug section
second of all when I ran "run and debug instead", vs code claims to be attached to unity as it can be seen in the lower part of this image.
however when i play the game in the editor, there is no option to use the steppers or even check the variables
on top of that the left dropdown list of variables is empty
what do I do? I have been following tutorials exactly but can't seem to get the same result...
json is a data file, you can only debug code
i did debug code, sorry for not showing that
i set the breakpoint in the singleton which initialises when the game starts
public class MyPointer : MonoBehaviour
{
private void Update()
{
var mouse = Mouse.current;
if (mouse is null) return;
var move = mouse.position.ReadValue();
Debug.Log(move.normalized);
transform.localPosition = move.normalized * 5f;
}
}
i'm trying to use the new input system to make a basic aiming reticle type thing. Whilst this does track mouse movement, it only moves the reticle sprite in a circle around the player but i don't know why. I tried switching between position and localPosition but that made no difference. The Debug statement prints out a Vector2
oh, and i have the CinemachineCamera set to look at MyPointer
mouse returns a screen position, so you need to convert that to a world position to use in transform.position
Is there a specific tutorial you're following? Because last I knew debugger in vs code wasnt supported.
using this one https://www.youtube.com/watch?v=-AgcVsS-rtQ&t=328s
In this video you will learn how to configure Visual Studio Code for Unity development. You'll learn how to get many things working including syntax highlighting, debugger, auto formatting, and snippets.
hey
i am encountering a trouble with position of UI when i instantiate a prefab object
Typically the best way for UI elements and layouts is to use the form of Instantiate that takes the parent Transform as a parameter directly.
i want to right click on a UI button
i added listener for right click
on that right click i want to instantiate a prefab like a menu over that UI button
but the problem is the position of the instantiated object
lets suppose i get the cursor position when right click and instantiated the prefab there
now if the UI button is on the bottom of the game then the instantiated prefab will be outside the canvas
i dont know the solution to such problem as its my first time encountering one
any helps are appreciated?
thanks in advance

why? What does your code look like
how and where are you spawning it?
nothing to code cuz i dont know how to set the position of the prefab
get the button's recttransform and set the prefab's recttransform according to that
In Instantiate
recttransform.anchoredposition
good idea
as rects are universal
but i have never worked with rects before
any guide that can tell me how they work

ok
sorry not rect transform but rect
rects are universal
but basically you can just add a bit to the y value of the buttons recttransform's anchoredposition and set the prefab's recttransform's anchoredposition to that. and then maybe you also have to change the rects' pivot point
ok but i just dont want to add everytime
consider a button that is on the top of the UI
then doing so will again put it out of the canvas
need a better solution
if its too high, lower the y instead
how to check that condition thats the problem
the fact is that positioning this thing properly depends on several factors, the largest of which being:
- What Canvas render mode are you using?
camera
IIRC you can basically do ScreenToWorldPoint on your mouse position and use that result directly for a Screen Space - Camera canvas
Otherwise - use this https://docs.unity3d.com/ScriptReference/RectTransformUtility.PixelAdjustPoint.html
let me see
ok i got the position
now how to determine if the position is too high or too low the overall screen or in the middle
hey
is there a way to post process screen spaced canvas
try changing the render mode to screen-space camera
and then assign the camera that has the post processing effects on it
dont want
i want to keep the screen spaced
due to some heavy rect stuff i am doing
if u want to keep it overlay there might be some work-arounds to get post processing
i tried googling
but found no hope
so asking here now
let me see
i dont think it will mess w/ ur overlay stuff..
it just adds and focuses a camera on it
i wont know unless i read or try
doesnt work with screen spaced overlay
Use screen width / height and compare it with x , y of the button.?
Combine it with pointer events which contain important information about clicks.
i am new with code and i would like to set a public GameObject Cube; to already be there when i put it on an object like i can with a "public string text = "text""
you have a couple of options, you can either assign it in Reset() using a method that searches for the desired object (like GameObject.Find if the object is supposed to be in the scene), or you can assign a default reference in the script's import settings, but that only works with prefabs. both of these options are also only really going to work for when you add the component via the AddComponent menu in the editor
A GameObject reference cannot be set with a literal value in code like a string can
so you need to get the reference some other way. Either assigning it in the inspector, or with some other code in a function later.
ok thank you
Im trying to save my UnityEngine.Random.State however, it doesn't seem possible. to load it back in as the values just get 0'd out.
Is there any possible way to do this?
how are you saving it
public Serializable class with a UnityEngine.Random.State property that I assign before saving to a json file.
and have you confirmed that it has been saved correctly? and that you are also correctly deserializing it?
property ?
[System.Serializable]
public class GameStateData {
public UnityEngine.Random.State seedState;
}
public void Save(){
data.seedState = Utils.GetRandomState(); //Returns the current state.
//Saves to Json using JsonConvert.SerializeObject
}
public void Load() {
//Load from Json using JsonConvert.DeserializeObject<T>(LoadJson(inFileName));
//Checking the seed state here shows all 0's.
}
ah yes, truncated code that doesn't actually show you doing anything or even how you've confirmed any of this actually works as you intended
Theres not much else to show at the end of the day. I store the seed state into a class, Serialize the object using Newtonsofts Json, look at the json file, and it shows it as being empty.
although if i were a betting man, i'd say that whatever "Utils.GetRandomState" is, is probably where your issue lies
And in editor, it shows the proper values.
well until you stop cropping out important context, i'm not going to bother helping so good luck figuring this out
Will do.
I'm fading out a sprite. The debug.log is showing a smooth progression from 100 to 0 alpha, but the actual sprite during gameplay doesn't fade at all until it hits 0 alpha, at which point it vanishes, and the sprite render doesn't display the alpha changing until then. What the heck..? If I manually drag the alpha slider it works fine.
Color uses values from 0 to 1. Color32 can use values from 0 to 255, neither use 100 for 100% alpha
sounds like you've got your color picker set to HSV
okay well those values you see don't directly correspond with the values you would use for the Color or Color32 data types. set it to 0 - 1.0 for the values you'd use for Color and 0 - 255 for Color32
hey there's like a split second delay between all of these audio clips playing and it's distracting because there's music baked into them. Does anyone know how to get rid of the delay?
could try making the wait be like 0.01f or something less than the length
Ok yeah there's a tiny skip but it's far less noticable, thanks!
Anyone got a video i can watch to learn C# coding USING unity
you can !learn this course of unity or use any C# video on youtube to learn C# solely
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I would recommend by learning from documentation and using unity tutorials as a reference, since if you solely use tutorials from youtube you will learn nothing
there is this tutorial from Imphenzia which I heard was good for beginners
https://www.youtube.com/watch?v=pwZpJzpE2lQ&ab_channel=Imphenzia
EXPAND for Time Stamp Links -- This is the most basic Unity tutorial I will ever make. If you are brand new to Unity, or if you want to make sure you’ve covered the basics, and if you want to learn how to write your first C# script - this is the video for you!
Over the course of 2 hours, I go through the User Interface, Game Objects, Transforms...
so I'm trying to use daves tutorial for fps camera movement and whenever I try to use his code that he shows the console says that Imput, sensY, mouseX, and mouseY dont exist for current context, and Time does not contain a definition for DeltaTime. I tried looking this up but could not find anything to help me. can anyone here tell me why this happens?
also I am not just relying on tutorials, I was just using this one so I can start somewhere
This is the tutorial. https://www.youtube.com/watch?v=f473C43s8nE
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
you copied it wrong i assume
for sure you did
hmmmmmm, ok
Imput DeltaTime these things dont exist
probably wrote it wrong, these are just custom variables i think so you named the variable a but in your code your trying to use b
hard to say without seeing the code though
but you should be able to figure it out
imma look at the pdf in his description, it may explain it
You didn't define the variables (sensY, mouseX & Y), and you misspelled "Input" as "Imput"
guys what is the best way for getting trigger in some animation ( like an attackt animation combo)
greetings. want to make it so that when i interact with an object the camera zooms in to the object so that the player can interact with it further. is cinemachine state driven camera the best way to do this. I just wanted to check and make sure that there isn't a more efficient way before i commit to this.
it is the best way ı think
anyone has any idea?
getting a trigger?
ı want a spesific trigger for a attackt animation
if ı attackt with hammer animation for example it should be more slow hammer collider or a katana is too fast
how can ı use this coliders exactly. This colliders should be there for just attackt actions
ı dont even know how can ı search this thing on internet and ı asked here
my english not that good btw.
slow hammer collider? what does collider have to do with speed
do you want to enable/disable colliders during the animation?
ı just want to make effective the colliders with attackt animation and move
yes also this
yes, for this you can use animation events.
ı want to change location of it to where ı want same like elden ring or black myth wukong games
you want to move the colliders?
but when it effects with collider it will be Player tag pr something
ı want a spesific collider for thıs anımatıon
yes
then you should separate the weapon hit colliders from player colliders
ı dont know to doıng that That ıs what ı askıng
ı need to learn the even just title of this
so ı can search on ınternet but ı cant fınd
not this one ı already know basicly animation and using animator
So what you want = when an attack animation plays you want the colliders to be active and look for contacts and disabled for certain animations, you also want to move the collider(I guess with your hand or if you have a sword), Is that correct?
ı want a spesific one
yes and when it touch any enemy there wil be effect
but if ı do it with in player colliders or something it wıll be by Player tag
no problem, that isn't hard.
ı dont want the tag wıll be Player or somethıng
1.Open the animation window and select your attack animation
2.Attach a script that will listen to animation events on the gameobject containing the animator component.
if you telling about using animator ı already know it
No i am not, i will get your job done!.
Do you know how to add animation events?
with clıckıng top of frame part
my attackt collider should be unknown
even if ı can do it with some other gameobject's collider ı need to know how can ı contact them
oh thats simple,
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Any help here?
//stop building part make the drag and drop system wont works
when i delete that part it works again, but i should not delete it because i need it for my building system, Ghost thingy
you need a script on the object with your collider which will have this code : private void OnTriggerEnter(Collider other)
{
if (!other.CompareTag("Player"))
{
// play effects
}
}
This function tells if the trigger got hit, it gives you a ref to the other collider, Also make sure to set the collider of the (sword) to istrigger., now in this function you can check if the trigger is not equal to the player tag.
actually look
like a raycast
it is not connecting our colliders
but it effects and ı can get ınformatıons
but it is just going one way
ı cant scale it or move good
it is controlling from inside code
and unknown
so you want to raycast from the (sword) starting point till the ending point?
and use that instead of hit boxes?
no just asking is there any better option than raycast for it
easy to controll and getting informations
and ı can connect with animations
best way is animations right?
ı mean animation window
there are two ways, the first one is having a script listen for trigger collisions and using a raycast, raycast would be slitely innacurate as the sword is 3D while a ray is a flat line,.
if you want to get information the best way is the raycast, the triggers are the easiest
you dont have to use the shape of a line, use Overlap or other casts
yes, but that wouldn't be performant, i think triggers is the best option.
rays are cheap
"other casts"...
most physics queries are, esp if nonalloc mode is used
handling these is also a bit harder.
when enemt get effects by player's collider, enemy will take information of ' Player ' tag
ı dont want this
that ıs all ı want
ı want something like collider
what effects ? particle effects
but ı wıll put many anımatıons of attackt and they should be dıfferent each of them
you're like confusing the question tbh
ı mean the influence My englısh not very good
what kind of game mechanic are you doing ?
you need to have multiple effects as prefabs, then using animation events you can spawn the correct one.
at the contact point
like this
this attackt trigger exactly follows the attackt and it influence player anywhere and anytime it wants
what ıs the way of doıng ıt
this means the enemy needs to talk with the player, So you can use an interface
like this : public interface IHittable{}
and inside the body of the interface you define the functions to do stuff in the player,
maybe ı should create an empty game object and creatıng all triggers here and contacting wıth maın player
so like :
public interface IHittable
{
void Hit();
}
Then your player script would :
public class Player : Monobehaviour, IHittable
{
public void Hit()
{
// in here is where you would do your falling animation or rolling animation
}
}
your enemy could then do a try get component of type IHittable and then call the hit func if it is not null
yes probably thıs should work
before thıs ı need to learn ınterface from youtube or smth
@cinder schooner thank you buddy <3
hey i need some help with the tree placing tool on terrain
it says that my prefab has no valid mesh renderer
but i checked and , i think it has
so i tried to convert multidimensional array (well. technically array of list) to json using JsonUtility.ToJson but it doesnt work.
is it possible with array of array, list of list or list of array ?
tbh im very suprised it is not possible to do it directly, i only need 2 list currently but its very likely that ill need more in the future. my online seach leads me to using newtonsoft extension but i want to build from scratch.
Hi, does anyone know how to do random item spawning in Unity?I have an item of one type that the player has to collect but I would like it so that each game spawns 8 items in a different place, for example I set 20 spawnpoints.
Copy the spawn points into a list, choose one at random via Random.Range, put it into the result list/queue/stack, remove it from the starting list
Repeat 8 times, use result list/queue/stack to spawn items
Another way is to just shuffle and iterate through the spawn points pool and either choose one or not based on chance = needed_left / in_pool_left
in_pool_left decreases with each iteration, needed_left decreases only when a spawn point is selected, so at one point if nothing is selected you're at least guaranteed a 100% chance to finally select something from the end of the pool
thanks
Im making a dungeon generator and what im doing is picking a room prefab, then getting its collider2ds size, seeing if it fits, then spawning it in, however, the size is always 0,0 for some reason?
Not sure how to help if you don't share any context or code
!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.
Bounds roomBounds = new Bounds();
roomBounds.size = roomToSpawn.GetComponent<Room>().roomFill.GetComponent<Collider2D>().bounds.size;
roomToSpawn is a reference to a prefab, and the roomfill is an object with a collider that is the size of the room.
bounds is a struct so you could probably just assign the room bounds the bounds unless you're not wanting the other details.
the size is still 0,0
Other than that, log the room prefab and it's bounds to see if it's correct
For example: cs var bounds = roomToSpawn.GetComponent<Room>().roomFill.GetComponent<Collider2D>().bounds; Debug.Log($"The room name: {roomToSpawn.name}", roomToSpawn); Debug.Log($"The room bounds: {bounds}", roomToSpawn); Debug.Log($"The room size: {bounds.size}", roomToSpawn);Edited
Where clicking any of those messages in the console window would highlight the room in the scene.
Show us the logs
i know the bounds are correct because when i tested instantiating it in the bounds are correct. (though im not going to spawn the room in every attempt to make it run faster)
ill try the debug stuff though
The room name: SHOP-ROOM
The room bounds: Center: (0.00, 0.00, 0.00), Extents: (0.00, 0.00, 0.00)
The room size: (0.00, 0.00, 0.00)
bounds are in world space, maybe they don't really exist if the object isn't instantiated in the world yet?
yeah, I think you want collider.size, not collider.bounds.size
Hey Unity hive-mind! I've been racking my brains over this one. I'm trying to render a grid on a plane and this is my GridManager.cs script. I get weird artifacts when I hit PLAY. I have another script GridVisualizer that handles the actual lines. Do you know what the reason for this could be? Thanks!
https://hatebin.com/vohdfcidaj
Why cant i apply my idle sprites to my animation controller
You're using a single LineRenderer, so when you go to the next row/column you get a "diagonal".
You should use multiple line renderers (easier), or make it so the loop makes the lines go in S-shapes so you never have diagonal positions (harder)
Hi everyone, I want to change the weapon name in a Unity 2D game on Steam. Which file should I look for to edit the item name?
Hello, so i am trying to use the new input system and i couldn't find a way to let the character constantly jump. I need to press the jump button all the time. What is the fix for it? Can somebody help?
We don't help with modding/decompiling/reverse engineering of 3rd party games here.
ok thank you
Try with the performed event instead.
Alternatively you can subscribe to that and the canceled events, and set a boolean variable to true/false. Then check the variable in Update
Thanks for your help. Is a LineRenderer the standard way to render grids for something like base-building/city-building game in Unity? I'm trying to create a grid so that I can place 3D objects (i.e. buildings) of varying dimensions.
There might be a Grid component that you can attach to the object
See if that exists
It does, but it's more of a placement helper
So I think you'll have to roll your own, or find an asset on the store that does it for you
Why does my running animation look like this?
so i found it. you have to wrap it in struct. so List<MyStruct> elements , MyStruct then contains List<string> data.
I have a bit of a problem rn
transform.position += transform.forward * 10;
this code doesn't work for some reason
it says "Object reference not set to an instance object"
everything else works fine
Show the full script and the full error message
Alr
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerRayCast : MonoBehaviour
{
public float cooldownE = 10f;
public int energyQ = 60;
public float cooldown = 0f;
public GameObject Player;
Ray ray;
RaycastHit raycastHit;
Vector3 RayPosition;
void Update()
{
cooldown -= Time.deltaTime;
ray = new Ray(transform.position, transform.forward);
if (Physics.Raycast(ray, out raycastHit))
{
if (raycastHit.transform.tag=="wall")
{
RayPosition = raycastHit.point;
}
}
if ((Input.GetKey(KeyCode.E)) && cooldown <= 0.0f )
{
if (raycastHit.transform.tag != "wall")
{
transform.position += transform.forward * 10;
cooldown = cooldownE;
}
else if (raycastHit.transform.tag == "wall")
{
transform.position = RayPosition;
cooldown = cooldownE;
}
}
}
}
Full error, including the line number
but I assume it points to the if (raycastHit.transform.tag != "wall") line instead because that would be null if the raycast doesn't hit anything
right, line 31 is if (raycastHit.transform.tag != "wall")
Hello, so ive been trying to use dot product to accomplish a goal which is making the screen to turn red with full screen pass renderer as the player does a 180. The screen effect(it turning red) percent will be connected as the player turns around so it wont be at 100% unless the player has done a full 180, this is why im using dot product. There is no certain trigger and this will happen when i press play. I would like the ditherspead float to change according to the player turning and dither spread(float) starting at 0 and hiting x when the player does a full 180.
But Im so confused using dot product and looked everywhere to help with what im trying to do.
https://pastecode.io/s/kwbp6dmu
here is the code I have so far. What you see is how far I got with dot product and me testing everything with the press E to make sure the screen renderer works
hey guys, uhh watching a tutorial for the state driven cameras on cinemachine, just found out you need to parent the virtual camera to the cinemachine brain... kinda already parented the virtual camera to my first person character/controller and did a shit ton of code surrounding it. anyway to do this without redoing the entire project?
Instead of dot product it would be easier to use Quaternion.Angle which gives you 0-180 depending on how much the player has turned
Then you can divide that by 180 and plug it into the lerps
sorry for late reply, Ive been learning about Quaternion.Angle n all that but thank you
discovering Invoke() after using coroutines for the smallest of things is actually crazy, such a time saver.
They do differ though
https://www.codinblack.com/how-to-run-a-method-at-certain-time-intervals-in-unity/
The last difference between Invoke and Coroutine which we will cover is the execution condition after the deactivation of the object. Invoke and InvokeRepeating do not stop after the game object is deactivated. On the other hand, this not true for coroutines. They stop after the game object is deactivated or destroyed. Therefore, you should use Invoke or InvokeRepeating, if you would like your method to continue running, even though the object is deactivated after the method is triggered.
would I need a second object to track the player doing a 180?
You can just use the camera's current rotation
and you already store the initial rotation
hi, ive just joined to try and find some help for a little camera rotation im trying to do, going onto unity in 3D after using GameMaker is a bit of a headfuq lol
where should I ask?
doesn't Invoke run once? (disregarding InvokeRepeating)
heres fine if its code related
Sweet :) Well ive just been trying to a feature into my camera, where it starts facing straight up then lerp down to an angle of ("-0.18") on the X axis. Ive had a go but its giving a really weird outcome lol. Heres a vid and the code on the camera :)
You can see the camera angles on the right in the video going like mad lol
well first of all your time for the lerp is 3? lerp is 0-1 im pretty sure
I did try with 1, gave the same effect, i increased it to 3 so I could ssee what was actually going on
its giving me an error cause its a vector 3
Make it a Quaternion and then startDirection = Camera.main.transform.rotation
Ah, you mentioned coroutines so I had thought it'd be for more than just a one time yield/delay/non-repeating function.
So what do I replace this with (srry I replyed very late and pinged you)
You have to put it inside the first check that makes sure the raycast has hit something
Alr
oh no i just stupidly made a single corroutine because I had no clue what Invoke was
and i just know learned of its existence
so goated
Also which one is the first check?
The first if statement in the code
Alr
Hey, I am having some problem with my game, when i play it i get an error where it complains on row 48. https://hatebin.com/qhivnemjmy
I am not sure if it could be due to a mistake in one of my other scripts
okay, I can now log 0-180 to see the rotation being printed live as I turn with
float angle = Quaternion.Angle(startDirection, _180Direction);
Debug.Log(angle);
but how would I go about implementing to lerp a float with it?
Take the lerps from the coroutine and replace elapsedTime / _hurtDitherFadeInTime with angle / 180
are you going to share the error or are we supposed to just guess?
so cardScript is null
okay, I will see the hand array in my playerscript contain any objects, if that's the problem
also that says line 52 which does not match with your script
yeah removed some notes before sharing it
ok, so if you expect help the least you can do is provide accurate and complete information
that's my bad, sry
move like some sort of camera? wdym by that?
also the slerp is hella wrong
that doesnt explain what you mean by that..
anwyay fix the wrong Slerp first and go from there
right now the Slerp is saying Turn the transform.rotation in this look direction but only give me 15% of it out of 100%
you should not be using a constant
thank youuuuuu
Ive got it working and I was messing around but I cant seem to fix the rotation issue. The screen effect also happens if I look up and down, I only want it to effect the y axis rotation
The easiest way would be to use an object that rotates only on the Y axis with the camera. For example if you have a separate player model then take its rotation
Hey, why am I not able to call the method I defined above? Am I missing something? It doesn't autocomplete to it and gives me an error for trying to call it
You've named the variable the same as the method
Is that not allowed?
It can't know which one you mean. It's trying to call the variable
ill try this when I come back, thank you again for the help
Hey, why does the playerMovement variable get set to null? I checked and the player variable doesn't get set to null, only the playerMovement is, and I'm absolutely sure the instance rocket has this script.
player does NOT contain a PlayerMovement component
But it does...
and is that the only gameobject called Rocket?
yes
ok, Debug.Log the InstanceId of player
This is the scene hierarchy
It returns -1284
ok, now switch the Inspector to Debug mode
yep that's not the ID
told you
How is that possible?
there you go then
I'll just change it's name to player
why not make a reference and store it in GameManager, presuming that is a Singleton?
then you can lose the Find completely
Because the script I'm using is on a prefab
does not matter
Really?
really
What if the prefab is in a different scene
would that just land an error>
oh wait nvm
as long as Rocket and GameManger are DDOL, no problem
I thought you meant something else
And then I need to reference GameManager in the asteroid script, so wouldn't that be the same problem?
Not sure where else I can post this without interrupting , sorry .
I'm trying to get my camera do a simple lerp to a new rotation on ONE axis ( like the video attached ) .
I've tried with some code to get the camera angle to just change up and down before adding lerp, and it offset my camera Y rotation for some reason when turning my player object? ( I've attached the code I tried using )
same solution
Camera.main.transform.eulerAngles = cameraRotation; seemed to be the line causing the weird Y offset, i dont know why it did that though , the X axis changing on button pressed X and C worked fine though
you were seeing this in the inspector?
nothing there will change the y rotation
Exactly, which is why im confused !
heres a demo of the outcome when the script is on, its changing the camera Y rotation . When off it shows the expected outcome
My player movement controller references euler angles aswell for the movement is this why maybe?
So what did I ask you, to which you replied no?
Ah sorry, I misunderstood you
the answer is simple, ignore the inspector
when you do
eulerAngles->Quaternion->eulerAngles (which is what you are doing)
the resulting eulerAngles will almost never be the same as the originals but the actual rotation will be
yes
A Quaternion is a black magic box that represents a rotation, correct?
if you say so?
dont you know what a Quaternion is?
ok. transform.rotation is a Quaternion
transform.eulerAngles is a Vector3 which can be set with degrees which you and I understand.
Internally these degrees are transformed through black magic into a Quaternion and stored in transform.rotation
now..,
when that Quaternion is turned back into eulerAngles to be shown in the inspector the values are different because one Quaternion can be represented by many euler angle combinations and the system just choses one of those which is almost certain not to be the one you put in in the first place
ahhh that makes more sense
yeah that helps
so what would be the correct way to go about it to stop that mis-representation
hence 'ignore the inspector' just take it for granted that the rotation represented is the correct one
you cannot, that's just the way Quaternions work
i think you might have misunderstood me , unless there is genuinely no solution for my game-breaking issue?
there is nothing game breaking there, you are looking at the inspector data and thinking it is wrong when it is not
no mate im looking inside of MY game. The video shows me playing with the script on, then without
the first button I pressed in the video is left, which should turn the camera left to look down the corridor as shown in the inspector and later shown by the working demo in the video
then why are you constantly refering to the inspector in your vid?
To show that its changing my cameras Y value when my player turns , when im only trying to get the camera to look up and down on the X axis when pressing X / C
you have totally ignored everything I just explained to you
Because im just confused now
lol
after you saying theres not a correct way to go about it
what don't you understand about 'ignore the inspector, the values you are seeing are not what you expect but the rotation they represent is what you asked for'?
right im sorry mate, but it just seems your way of explaining things doesn't work with me personally , i'll find help elsewhere because your just being unnecessary
good luck with that
Having a brain fart.
Building up a simple spaceship controller (steering dealt with by the mouse and movement driven by physics.
I'm getting a lot of 'jitter' when moving.
Video for reference.
https://streamable.com/o07oaq
Full controller code
https://hastebin.com/share/awekuvocak.csharp
I'm 99.9% that the following is the culprit and I know why, but my brain isn't cooperating and I can't think how to 'blend' the vertical and horizontal movement (if that makes any sense)
void MovePlayer()
{
playerRigidBody.AddForce(transform.forward * playerFlightSpeed * moveZ, ForceMode.Impulse);
playerRigidBody.AddForce(transform.right * playerFlightSpeed * moveX, ForceMode.Impulse);
}
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm using Addressable to create a Scene conversion and I get an error called Error unloading scene MainMenu: Attempting to use an invalid operation handle. But the scene conversion works well. How do I fix the error?```csharp
private async Task UnloadSceneAddressable(string sceneName)
{
if (_loadedScenes.TryGetValue(sceneName, out AsyncOperationHandle<SceneInstance> handle))
{
if (handle.IsValid())
{
try
{
AsyncOperationHandle<SceneInstance> unloadHandle = Addressables.UnloadSceneAsync(handle);
await unloadHandle.Task;
if (unloadHandle.Status == AsyncOperationStatus.Succeeded)
{
_loadedScenes.Remove(sceneName);
Debug.Log($"Scene Unloaded: {sceneName}");
}
else
{
Debug.LogError($"Failed to unload Scene: {sceneName}");
}
}
catch (Exception e)
{
Debug.LogError($"Error unloading scene {sceneName}: {e.Message}");
}
}
else
{
Debug.LogWarning($"Handle for scene {sceneName} is not valid. Removing from loadedScenes.");
_loadedScenes.Remove(sceneName);
}
}
else
{
Debug.LogWarning($"Scene was not loaded: {sceneName}");
}
}```
you mean unity stuff. and its because your ide isnt configured !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
• :question: Other/None
Fixed, thanks!
try Camera.main.transform.rotation = Quaternion.Euler(CameraRotation); //use localrotation if the camera is a child of an object this should work
also this wont lerp but should fix the other problems you mentioned although I didn't test it though, so hopefully it does work.
why wont this work, it keeps saying cannot convert vector3 to float but doesnt it need numbers in order to change the rotation?
if (Input.GetKey(KeyCode.A))
{
rb.rotation = new Vector3(rotSpeed, 0, 0);
}
2d rigidbody uses a float for its rotation since it is only around the z axis
unless rotSpeed is a Vector3, in which case why are you using it as just the X axis of a Vector3?
which is the issue, the fact that you are using a 2d rigidbody? or that rotSpeed is a Vector3?
im using 2d
read this again, but carefully this time: #💻┃code-beginner message
use a float, not a Vector3 because the rigidbody's rotation is a float
ohhhh
also note that assigning rb.rotation assigns a specific rotation, not a speed at which it will rotate
yes ik i just didnt know what to name the variable
im having another issue and i think i know the problem I just dont know how to fix it
im trying to make a remake of the astroid game if you know it, youre basically a small spaceship and you have to shoot astroids before the hit you or you lose
I want my player to move in the direction its facing but it only moves in one direction regardless or the rotation
here is my code
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float speed;
public float rotSpeed;
public Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKey(KeyCode.W))
{
rb.velocity = new Vector2(speed, 0);
}
else
{
rb.velocity = new Vector2(0, 0);
}
if (Input.GetKey(KeyCode.A))
{
rb.rotation = rb.rotation + rotSpeed;
}
if (Input.GetKey(KeyCode.D))
{
rb.rotation = rb.rotation + -rotSpeed;
}
}
}
does anyone know why unity wont download?
assign its velocity to transform.up * speed or transform.right * speed (depending on the direction the sprite faces when not rotated) instead of just new Vector2(speed, 0)
okay thank you i will try it
not a code question. but go through the following check list and ask in #💻┃unity-talk if you need further help after going through the checklist.
!install
- Make sure you have enough space including on
C:drive. - Check that it's not being blocked by antivirus/security programs.
- Look through the logs for a real reason why the setup fails they are pinned [here](#💻┃unity-talk message).
If you still have issues, perform a clean install in another location:
- Install the Hub and Unity in a non-system drive or a clean new folder in the root of
C:drive. - Failing that use the recovery Refresh option or reinstall OS entirely then repeat the previous step.
okay it works now thank you
only problem im having now is that when i rotate it slows down my movement alot
im almost stationary while rotating
i fixed it
it was because it was in Update not FixedUpdate
The info that I provided still applies though. For instance, if you had something that would delay a few seconds before executing but disabled that object, invoke would still fire and do it's thing regardless of the state of the object. Which could potentially do something you aren't expecting.
This is a coding channel for help with code. Maybe #archived-game-design
Hi, I know that for the x and y axes, we can use the Tilemap Collider with a Composite Collider, but I need to use a Tilemap on the x and z axes. I had to create my own script for generating colliders from my Tilemap. It was quite complicated, especially regarding optimization, and I wanted to know if there is a better way to do it.
Thanks.
The generation time is very good, but I'm bothered by having so many colliders in a single GameObject. It feels like something isn't right.
I know this is a very general question but does anybody know how people get to be able to be such good coders who just know what to do because Ive been trying for a while but can't progress much.
You learn out of necessity
"I need to make a script that makes this bomb explode"
Search on how to do that, make it work and then you'll have knowledge for future coding that doesn't necessarily have to do with anything you did before
pretty much, break down the bigger problem into smaller easier to solve parts that all come together for your feature
If you really want to code, I recommend starting with algorithm projects in pure C#, then moving on to programs with simple graphic libraries, and finally creating a game. Starting to code by making a game is like wanting to run before you can walk, in my opinion
Keep in mind that you can make very good games by being an average developer, it depends on the "difficulty" of your project
Sorry to bother but were exactly would I find algorithm problems?
well you can start with a small program that returns if the date entered by the user is a leap year for example
if you want smtg more complex you can do a tic tac toe game in the console for exemple
my first C# project was a linux terminal but in windows, with some commands and stuff, i used the same project idea when i started to learn C++
if you wanna learn how to code you gotta know your understanding level, some people understand stuff faster and some people take more time, dont learn from youtube because you will be tempted to only copy and paste stuff, go to forums and read documents and stuff, and after that go watch youtube tutorials and try to get ahead of the guy ur watching
If you want to get better at pure logic or problem solving, use a website like leetcode or whatever else you want.
If you wanna get better at unity specifics, then try to create stuff that you find interesting from other games.
Making stuff in console wont get you nearly as far as doing the actual hard problems from websites. And at least websites have ratings like how hard a problem is, plus testing to see if your solution works
Thanks guys for the help I will try these
learn base C# (the syntax and stuff like that) and then slowly move on towards the unity api, learning pure C# will take a while and without a specific use it will he hard to learn, hop in unity, read some stuff and the try to do it yourself, good luck
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
rb.AddForce(car.forward * vertical * Acceleration, ForceMode.Acceleration);
}
I made this for a car controller, but it just doesn't move. I've assigned values to everything but it just doesn't move.
dont read input in fixed update
GetAxis should be fine
How do you declare and fill a dictionary in the same line?