#š»ācode-beginner
1 messages Ā· Page 441 of 1
just post it here dawg no one rlly cares
Don't post it here if it's not related to code.
Honestly I'm not sure what your issue is, because the original text doesnt make too much sense.
expected result
actual result
Did you look at the scale of how you have it in the expected result, because I'd suspect that your original laser is longer on the y axis
wdym
I'd also try to use like a line renderer here instead where you can define the start and end point
- Don't
- Respond with "wdym", "?", or "didn't work" without justification.
#854851968446365696 - Please elaborate
Like your object at 1,1,1 scale might not actually fit within a box of 1 unit. For example if you look at a player model, the scale is all 1 yet the model is clearly taller than it is wider
Also im just speculating at what the issue could be, since the code made sense logically from what I skimmed through
the scale isnt multiplied or added or anything, it is directly set so im not /*p454\
]+9-****
my cat stepped on my keyboard lol
the scale isnt multiplied or added or anything, it is directly set so im not sure how that would matter as much
the texture is a 600x600 square
Still, did you look at the scale of an expected result and compared that to the actual distance between objects?
It doesnt matter if its being set or multiplied, I was saying that the visuals of the object might be larger than 1 unit which is why visually that could happen, though this is still speculation at the issue
the expected result is around 3 units long while the actual result is 9.00427
one thing that im kind of suspicious of is the use of local positions and normal positions which im not entirely sure if im using them correctly
sounds like a great place for some debug logs
ive been using a lot of debug logs so im kind of just giving those up now
I am following this youtube tutorial exactly how he writes his code after trying to change some of the variable names and getting an error but I am still having the same issue
https://www.youtube.com/watch?v=k-K2JWoEaS8&list=PLadYLGMfR6Lpvh3xX3a7LXbqJqY_WjIk7&index=6&ab_channel=GameDevHQ&t=4m25s
As in the video I applied MyPlayer to my game object which is a capsule instead of a cube but I know thats not the issue
Welcome to GameDevHQ Online Unity C# Tutorials
FREE BEGINNER TO ADVANCED UNITY C# TUTORIAL COURSES:
Check out our other youtube videos below, or Sign up officially at GameDevHQ.com and join a community of self taught developers who use our educational platform.
In this Unity C# Tutorial Intermediate video we discuss the continuation of cours...
thats the error code i am getting
need to assign myProperties to an instance of the class
like myProperties = new Properties();
MyProperties is null
Don't ever new() a MonoBehaviour
opps, was thinking general C# there
To reference the properties, you are likely supposed to use GetComponent in this case since it is a private variable. That is assuming the the object that has MyPlayer has Properties as well
Also, you seem to have a script called MyPlayer as well as Player, both of which have an error on the same line
Thats cause I renamed player to myplayer so i think that was an older error message
HA! In the video he GOT a nullref
oh shoot should i have watched further for my answer
He tries to do new() on Properities, which is very wrong
how do i change only my of the rotation?
I didn't watch more than there. It is a garbage tutorial
You cannot
Make a variable for rotation. Change z of that variable, assign the whole thing back.
whaat
ok
lmao imma not calling you a clown
Well, that is what it means when you respond to someone with a clown image
It is a very rude thing to do
its not that serious
didn't know thats the way ppl see this outside my country
guess thats just some cultural thing idk
im sorry not meant to offend you
not even near it
Ok, I accept that. Apologies for overreacting then. I have never ever seen someone use it in a different way. It is not really a cultural thing because this is the internet and I talk to people in all countries around the world
I do hope my instructions made sense and were helpful for you
i meant to say cultural of my part, like some ppl here use that instead of saying "oh"
it did thxx
They send a clown emoji instead of saying oh!? Well alright. Thank your for that insight. I will keep that in mind in the future.
I see it often, and it has always been meant as an insult haha. Meaning "you are a clown/fool"
ye its something near that
https://paste.ofcode.org/g2ajsTekQHhndQCzPxuR7i (WeaponUpgradeBenchManager script)
so im having a small problem , im confused on how i could like set the WeaponName adn WeaponIcon from WeaponUpgrades to the name and icon from the WeaponSO , i know i could do it in the WeaponItem() method but that supposed to only run on Start() method and i want the WeaponName and WeaponIcon to change based on what gun you currently have so it has to be in the Update() method but since my weaponUpgradesArr is an array , im not sure on how to do it icl
Hi guys, Ive got aproblem in which I have 3 menus that show three different types of objects but the information display in each of them shares some data like the name or the description of the different objects, however, there are some things that they don“t share, for example, weapons have damage quantity but resources don“t, any ideas of what should I do code-wise?
Well, how do you access an element of an array? That's like the very basics of any programming language.
What do you have so far?
How would I go about a script where when someone clicks on an object the object follows the mouse on a 2D game?\
Where's the best place for a unity package / assembly def esque question? #āļøāeditor-extensions?
Ive tryed doing a class with the data all of the menus should have and the child classes for all of them but with their exclussive data, however, when Iām going to display the data, the slots have a method that sends their own data for the components previously mentioned to display
However, if the display method is in the parent class, this doesnt include the exclusive data of the different menus so the slot can only access the parent class (because I dont want to create different types of slots for each menu so I can reuse code)
I dont know if I am explaining myself well
So the slot has a āDisplay componentā that calls the āDisplayInformationonMenuā component and passes its information but the component only stores the information of the common data between menus, if I wanted each menu to display its exclusive information I would have to creat a āWeaponsMenuā Component, āResourceMenuā component. These components are the ones I would have to access but I want to reuse code. Any suggestions on how the arquitecture should be?
What exactly does your Display component do? Can you share some code?
when you call Instantiate on an object, I'm guessing that's when it's Start() gets called and would complete before the next line of code executes after the instantiation
awake when an object is created
but is the Start() called after that and before it goes to the next line after the Instantiate?
wdym by " before it goes to the next line after the Instantiate?"
No, Start is called later on in the frame
oh Hrmm
At the start of the next frame to be precise.
if you want to wait for specific frame like physics, you can do coroutine
IEnumerator Start()
yield return new WaitForFixedUpdate()
if not physics there is also https://docs.unity3d.com/ScriptReference/WaitForEndOfFrame.html
etc
with an index between the []
not sure what index to put tho , since i dont use the weaponUpgrades array outside of the WeaponItem() method
0 i guess
The index of whatever element your data is in
Wdym? I'm confused
hi, i am planning to set spawn for each room, so that whenever the player enter the room, it'll create the player object accordingly on the spawn.
for example, the player exits through the red door, so when he comes back to that room, he's going to spawn from the red door.
here's how im gonna do it:
1.) create a spawn prefab with ISpawn interface to be landmarks
2.) set the Warper script so that it sets the spawn to the Spawn object's location every time the player interact with it.
3.) update the PlayerMovement script's Start function to set the coordinate to the spawn, so that it will spawn on the Spawn object every time it enters the previous room.
is my approach good?
I'm not sure how to clarify it any more than that..?
Your icon and name are in stored in one of the elements of the array, right? So you just need to get the data from the correct element.
Sounds good to me.
no no , WeaponName and WeaponIcon are just field i use so then i can set them correspondingly from the WeaponSO which i can get a guns icon and name
and i use them like this
So... What is the problem?
this is the problem
I've read that several time, and I still don't understand what the problem is
If you have a specific error, then share that.
im not having an error , its just the weaponUpgrades field is an array and im using it in the WeaponItem method where i set everything the name , quantity n such and i call the WeaponItem method in start cause if i do it in Update and i have one upgrade in the array , it will continuosly create that upgrade and i dont want that , so thats why i gotta set the WeaponIcon and WeaponName from WeaponUpgrades to the WeaponSO icon and name but since the weaponUpgrades field is an array , im not sure on how to go with this , tried a foreach but clearly didnt work , even a for loop but i realized it was stupid so im a bit stuck icl
How do I get the GameObject of a clone of a prefab, cause when I use the following code, it references the prefab and not the clone.
That's almost the same text as in your original question and it's still not clear to me what you're trying to do and what the problem is.
If you're already doing that in Start, then just do it similar way in update..?
instead of Object make it a GameObject
i alr explained why i cant do it in update.
Then what do you do want instead?
If you can't explain with just text, then maybe take a screenshot or a video that backups your text explanation
I tried but I get this error
even though it has an animator
and its not referencing the actual animator
its referencing the prefab
wait
i think ik why
to find out how i could get an index for my weaponUpgrades array in the Update method where im trying to set the Weaponicon and WeaponName to the WeaponSO name and icon
WeaponItem instantiates new objects and assigns the data from the array to them.
What you want is just to modify these instantiated objects? Is that correct?
yep indeed
Ok, then say that...
That's not an error, it's warning. But aside from that I don't know how it ties into the cardVariant. If you want the instantiated GameObject then use a GameObject for hte type, or cast it to one when you go to use it
Assuming you don't modify the order of the objects later on, the currentlyEquippedWeaponIndex, might correspond to the index of the data in your upgrades array.
I made cardVarient to a gameObject but the variable is not being set to anything
and documentation says Instantiate() returns an Object
Otherwise you'll need to keep track of data index in your actual weapons, so that you can remap the weapon index to the data index.
Everything is an Object, it's the base type
the currentEquippedWeaponindex is just an int field in EquipmentManager script and it basically changes absed on what weaponType you have in your hand but as an index
Then what I said here:
#š»ācode-beginner message
im a bit lost rn, cause Card Varient isnt being set to anything
and its not giving an error
It would be simpler if each of your weapons just had a reference to it's upgrades data.
so have a reference of my WeaponUpgrades in my WeaponShooting script which is on all weapons and then set the weaponname and weaponicon to the weaponso icon and name there?
Hover over Instantiate, see what it says it returns and what eah paramater is that it takes in. you are passing it a canvas it seems
Probably. I can't say for sure without having a complete grasp on your implementation.
should I be having an extension?
to hover over it?
You're on a mac, so I'm guessing you're using vscode three, and I don't know vscode, but I would assume if configured properly it should give you information when you hover over it
usually called Intellisense
how'd you find out im on a mac? š
I'm preceptive
Note that even thought the documentation does say Object for the return type and the prefab type, their own examples don't use Object, they use the inherited types of Object, such as GameObject
how does that make sense š¤
Well it's technically correct, it returns an Object, but if you want to use all the inherited methods you're going to just have to cast it to the type anyways
Anyone in here can help me with some code readign real quick?
Don't ask to ask, just ask
!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.
its back ticks also just use the Links for large code
its not a command
it says in the message what to do
ITs not a large ammount of code
just send the class and explain what "isn't working" means in this context
what do you expect to Happen vs whats happening
then you should configure that first and foremost
How do I do that?
check your !ide and click the link
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 ur right
but idk why it isnt returning anything
also what do u guys reccomend for keeping code tidy
cause my project is getting slowely bigger
and its getting exponentially harder to manage
follow good coding practices
did you put a debuglog after the instantiate call to verify it's not null?
im doing that rn
anything in particular?
there are a bunch of good stuff here
https://unity.com/resources/level-up-your-code-with-game-programming-patterns
code:
its not printing anything
i checked if the if statement is running, and it is
im guessing if its null, it wont log anything
that is not a very productive debug log
make the call, assign it to the gameobject then print if the gameobject is null
aight
though I'm pretty sure it either Instantiates the object or throws an exception
so put a print above the call, make sure it's even getting called, if not then you have something further up the chain wrong
ok but where is that error from?
not this instantiate call, as it doesn't seem it's even getting called
this line
yeah ik
this means cardVarient isnt assigned in the inspector
it tells you pretty much that in the error
it shouldnt be
well it is supposed to be
it should only be assigned in that line
you cropped out some important details in this image
from GameObject, yes
soz for the @
dunno about Object
thats the thing
me neither
doc is not showing anything about getting the GameObject from an Object
why are you spawning it as Object
what's an Object?
Show more of your code like what type is myCardvariant now?
alright, got it, never touched that though
can't think of reason to
correct you generally don't need to
as suspected, you still haven't changed them to GameObject
You should use GameObject instead of Object i guess
there is no error
ill try setting that to a gameObject
well stop reverting to Object
Instantiate will cast to whatever type you pass through the first perameter Object
so if you pass a Object it spawns as Object, etc.
thank you guys!
it works now
and one more quick question, how do I check if an animation has finished playing?
I want to make it so the instance gets destroyed after the animation runs
so Id make it run a script at the end of the animation where it destroys itself?
is this fine?
There's that use of Object again...
oh, he crops out details of the image
"Object" is basically the target here
i dont get whats wrong here
but if script is already on same object as animator then it will give you dropdow
look at the one from the manual
you have to select the object with the animator
while the animation window is open
then select the animation event there
the GameObject?
yes
did you read what I wrote? about the animation window, not animator. Only mentioned animator being the instance of your animation
my animation window is open
ok select the object with the Animator on it
then click the Animation Event in animation window
you still didn't select the gameobject with the animator
having the animator window is not the same as select the object with the animator component
you mean select it with the animator? or select the object which has the animator?
thing is the animation and the script run from the animation are on two different GameObjects
but im gonna move the function
so put another script?
i need help with some really bad lag
its been making me want to stop game development altogether because i cannot find the cause
please someone help me, the project isnt very big i started a week ago
don't ask to ask, just ask damnit
what
we cannot tell anything without details..
ohhh
on one can help you if you don't show where the problem lies
and what the problem is
okay anyways, ill be playing the game and if it runs for about a minute it seems randomly it starts lagging VERY BADLY to the point where its not playable
nothing is happening though
really bad lag
and I cannot find the cause
They said both things...
Yoo
Use the profiler and see what is causing the issues
liek in entercollision
where do i find that
complete a sentence before hitting enter
like in Oncollisionenter( collision collisioder)
It is a window under analysis.
You will be able to google it easily
how do i access collider.name and tags and stuff
mb mb
https://docs.unity3d.com/ScriptReference/Collider.OnCollisionEnter.html
use the Collider parameter
If its 2D , use the 2D version
The parameter gives you access to it.
Collision is a struct. You can find what it contains through the link nav sent
i read this, i cant find,
you looked at it, you didn't read it
Collision
Click on the large spiked portion
You cropped everything that could possibly be useful out
Google a youtube guide on how to use the profiler and follow it
!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.
The hierarchy view is usually far better than the timeline view
lookup tutorials on profiler. You have to switch from TImeline to Hierarchy view
Did you make a script called Collision?
so like this i assume
Yes
so EditorLoop is making it lag
could be , 276 ms is a lot
The issue will be in playerloop
Oh huh... true
Yeah that's an insane amount of editor overhead,
What is going on there
to know for sure, make a build and if its no lag you know 100% its the editor
Yess
Well, there is the problem
i made a build and it has the same problem
in-game
Do not make scripts named the same thing as unity classes or structs
Rename your class
Make the built game and connect the profiler to that
Move the frame it's checking around a bit. If it's Editor Loop for everything then ya it's the editor.
nope still there
something is wrong with your ide
!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
so if editor loop has the highest percentage then the editor is causing the lag?
I still see collision.cs at the top too
If it's still happening in the built game then it's not the editor
Connect the profiler in the built game
how?
See here
You can autoconnect the profiler
Ya. It's just during lag spikes caused by shit like Debug.Log or other editor specific stuff, the editor gets the blame on some frames and the actual source gets it on others. Just kinda click around a bit to see if it's always the Editor Loop.
Editor loop will USUALLY have the highest percent unless is a massive game
That's why I dismissed it at first. But this is a bit much
It'll auto connect to the unity profiler and start it
what
What about it? Your ide is not configured. Follow the guide I sent
#š»ācode-beginner message
Check hierarchy but odd that it's vsync...
it is
as mentioned , it doesn't seem your IDE is properly detecting unity classes
i did all of those
It is not
It is very clear it is unconfigured.
Vs code has issues sometimes
hierarchy shows nothing
nvm
Did you click on the spiked portion
Add the GPU profiler module and see if it confirms that
how, it litrelly shows same error in VScode and Unity, and intelisence isplays all functions and classes
Irrelevant
It is clearly messed up
Behaviour Uknown Word is not normal..
ah yes cSpell, whatever that is
Itās waiting for the GPU to finish rendering the frame according to QualitySettings.maxQueuedFrames
Turn on your GPU profiler
Like vertx suggested
okay then play the build again?
Looks like it is an extension you added messing things up.
Show Collision.cs though
You still have a script named that, verify that the class is renamed
If it is verify that renaming didn't rename the OnCollisionEnter parameter type
this is not normal
I presume that extension can just add words to the dictionary. Either way that's not the issue
the issue is declaring Collision again manually, and everything else is a distraction
yea actually you are right.
assumed they did remove the Collision class but apparently did not
I feel like they may have renamed the class which automatically renamed the parameter type.
Ah, no. Last ss shows that is not the case
Ah, they DID. It is lowercase now
@queen adder rename the class to something COMPLETELY different than collision.
Set the parameter type back to Collision (capital c)
how enable?? i pressed it
You definitely did more recording after adding the module?
what??
Did you play the game some more after enabling
Record more profiling data now
You need to record more profiling data if you haven't done so after enabling the module
aka let the game play a bit more
i dont understandš
Click play
Ok, look at the profiler again
Before the edit I misread your typo
are you profiling a build?
Ideally the build, as that's where you'll get data without the editor overhead.
okay i just open the build and it will start recording, correct?
You'll have to make sure autoconnect profiler is ticked
iirc you need to build as Dev Build too
Yeah it dooesn't let you autoconnect unless dev build is active
I was focusing on crazygaming, did the build have the lag?
It seems to be related to this
https://discussions.unity.com/t/occasional-performance-spikes-on-dxgi-waitonswapchain-without-a-gpu-bottleneck/940536
*this one is more comprehensive
To do GPU profiling in a build you have to disable Graphics Jobs in the Player Settings
Do your GPU profiling first, your case might be simpler.
okay since im actually stupid im very sorry but can someone give me a step by step guide on how to get it to record because it isnt anymore and i dont know what idid
Listen to what vertx said, go to your player settings (Bottom left of build settings), disable graphics jobs under "Other settings"
Make sure auto-connect profiling is enabled
Then build and run
is it better to use transform translate or addforce for the player controller?
completely depends on the type of game you're building
so while learning how script draggable item, i'm kind of struggles with the item keep snapping back to the start after i dragged it to where i wanted to, does anyone know what am i doing wrong ? (I also did exactly what the turtorial asked me to)
can you elaborate, can you give me very general examples on which would work better where? im doing a 2d game and just want to make character jump
Between those two choices I would pick addforce every time. But there are MANY other choices.
Big ones being setting velocity, MovePosition, and Move() from the CharacterController
Click the GPU usage->select the spiked region, check hierarchy
If you don't want them to be static, make sure materials that are shared by multiple objects of the same type have GPU instancing enabled
will that fix it
Not sure, can't say for sure. What we do know is that your mesh rendering is taking an obscene amount of time
For starters, that spike doesn't seem to be regular, so you should be thinking of what in the game causes it.
there is nothing going on in game!! its a box!!
Most of the time it seems to be 60 fps
Wait, is this just the Unity box?
How many materials are on this box
You should check what's going on when this happens:
Comparing the profiler data with the regular frames might be useful too
NOTHING IS GOING ON!! I DONT KNOW AND I FEEL STUPID BECAUSE I DONT KNOW WHAT IT IS!!
Click the material for your box
i didnt mean to seem angry but i feel like a idiot
Enable GPU instancing
Ideally
Since they're static
All those objects should be static
Well, maybe you look at a particular area of the world or something?
Or this repeats at certain intervals?
If you mark all the cubes as static, that would be better
See if that helps
You're currently doing 2 draw calls PER cube
When you can make it 2 draw calls for ALL cubes
Can you record a video of the gameplay including when it lags and not?
Also I'd look at the very first frame it goes wild in the profiler
do i bake afterwards
it won't be relevant for performance, mark and test
follow dlich's and vertx's instructions if that didn't help
still lags
yeah one minute
Next thing I'm predicting is that it's something to do with the player model..
Which will be shown in the video, I hope.
Okay so there ARE other things in the scene
yeah like a bunch of other cubes
Do you spawn anything via script?
nope
does it have to be individual cubes are can you make a mesh and just texture it to look like many cubes?
Are ALL the cubes marked as static?
yep
Click on the stats button in your game-view, and record your batches.
See if your batches rise when the lag starts
- I'd make sure there are no suspicious messages in the console at the time the issue happens.
- It's either something happening in the game(some code running, spawning more object for example)
- Or it could be that something else is tanking your GPU at that timing.
not rising
but you can see fps
only things in the console
To test the last theory, check the task manager to see what's using the GPU the most.
i only see cpu on task manager
It should be in the main tab as well. Where the processes are.
I don't think task manager groups by GPU usage in the main processes tab, default at least.
It does for me. Is it not enabled by default?š¤
Did you save the scene or anything
nope
Maybe the static stuff took a bit to... take hold
Close task manager and see if we have schrodingers GPU bottleneck š
Might be a malware
Maybe someone's using your GPU for crypto farming š
i dont download programs, and i make my own png for textures
so i dont think id have a virus
Well, either way, it seems to not be something unity specific
no more taskmanager, and no more lag
attach a special note to the game: must have task manager running while playing
no idea what happened
Build the game and see if it lags
okay
this is how im feeling right now since the lag dissapeared
until its built...
Getting a 400ms decrease in CPU/GPU time is any optimizers wet dream
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
void OnCollisionEnter(Collision collisionInfo){
Debug.Log(collisionInfo.name);
}
}
lag is back in the buildš
Check task manager now
Check usage
With the lag active
Sort by GPU usage in processes
And if nothing stands out, also check your GPU under performance
See if your VRAM or whatever is bottlenecking
And in the processes tab?
i donthave gpu
Odd, honestly..
If you close out the built game and try to play it again in editor, is the lag still gone?
Is that showing that much usage when it's not lagging?
thats while lagging
š
Yes, that's why I asked about when it's not lagging.
this is also while lagging but this time in editor
this is while not lagging (in editor)
Did you delete your own Collision class ?
That's weird. What is it writing to the disk?
The GPU usage definitely goes up during the lag
What
i dont know how to see disk
right click on Collision and Peek definition
you have made a class called Collision which is causing the problem, rename or remove it
its writing 77.4 MB/s
Yes, I see that. The question is what is that for? Assuming that's during play mode.
we have been trying to find that out for 2 hours
The writing to disk??
You're not reading correctly.
I was thinking that the increase of writing to disk could be the log files, but 78MB/s of log files is pretty crazy
okay i give up gamedev guys!! thanks for the help!!!
Profiler data maybe, if it's active?
If you can share the project I can have a look on my pc, but I bet it's something with your environment(potentially malware).
What we do know is that it's a case of the CPU waiting on something from the GPU...
This guy was able to track down the specific Wait target
https://discussions.unity.com/t/occasional-performance-spikes-on-dxgi-waitonswapchain-without-a-gpu-bottleneck/940536/3
That could be itš¤
But what exactly it's waiting on is not very clear
okay if you can find out how to fix it then thats better than restarting
@rich adder thank you
i fixed it
It's waiting for the rendering to complete. If the GPU is busy with something else at the moment, it would obviously take more time.
I'm aware of that, but what's making the GPU so busy
Maybe they're running an LLM in the background or something. Hahah
Or it's cryptocurrency mining malware.
Did you make this project entirely yourself? @queen adder š
yes
Here's a quick and dirty method if you want
Run the game
When it starts lagging, disable batches of cubes in your hierarchy
The render.mesh/shadows taking so much GPU time points to some mesh issue but it's hard to tell without the project in somebody's hands
I do have to hop off now unfortunately, I hope dlich can help with testing the project out!
@teal viper i would definitely run it sandboxed first š
Oh did you enable GPU instancing on your cube materials?
(And also do they all use the same material?)
wait oh wait
I just realized those cubes aren't prefabs
im going to bed
If you have the time... you can try prefab-ifying one cube object and re-using that. Make sure that GPU instancing is enabled for the material on the object you use for the cube. Since the static flag didn't work, I have my doubts this will, but it's worth a shot.
ill resolve this in the morning
Sleep is the best solver.
Also.. in case I forget.. try disabling all lighting to see if that helps at all
if (this is not Equippable)
{
return;
}```
Equippable is a class, does this work as I expect it should?
it's not giving me errors, but I asked my buddy chat gpt and it said it doesn't work, but then when I said it does work it said it works in newer versions of C#
nvm should be fine i think
i was thinking of is not null sorry
is not should work afaik
could just do if (!(this is Equippable)) but is not is more readable imo
Mornin' all,
Would someone mind having a quick look at my raycast code please? I really don't understand where I'm going wrong.
https://hastebin.com/share/lodoyekuni.csharp
I'm using LayerMasks to differentiate between different 'clickable' objects in my scene, but for some reason when debugging, the raycast returns true no matter what object I point at.
It all seems to be set up correctly etc. But I'm obviously missing something. š
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
was is not not working ?
it is, just never used it before so wanted to make sure I'm not doing something stupid
oh yeah is is good to go along with the not
You can store result variable to is
void A(A a)
{
if(a is B b)
{
b.Hello();
}
}```
yeah I'm using that in some parts of my code š
tbf, this is forcing a cast so is no different to
B b = a as B;
if (b != null) { }
tru tru. just looks so neat as one liner š
fair, I tend to use as if I want the cast and is if I don't
not long ago learned we can cast transform as RectTransform
amazing revelation tbh
I was curious whether is is faster than as and apparently not? https://www.danielcrabtree.com/blog/164/c-sharp-7-micro-benchmarking-the-three-ways-to-cast-safely
is is faster because it's a simple type check without a cast attempt
I mean, not only not, but it's slower š®
it does maybe depend on the circumstances, but yeah, you can check some benchmarks in the link above, was not what I expected
if you do
if (a is B b)
you are actually doing an is and an as so will be slower than either is or as seperately
that should be pretty much the same as as with a different syntax
and the benchmark linked above confirms it
but if (a is B)
is actually twice as SLOW š®
(specifically tested with an object a = "something" and if (a is string)
ah, no, I read their code now, it's just stupid š
so, yeah, I'd assume is is pretty similar in performance to as but of course it does make sense to use is if you only need the check and not the value
think about it, as has to do all the work that is does AND perform the cast, so there is no way it cannot be slower
Is there any reason why this wouldn't work and teleport the player? The respawn message is displayed but the player doesn't teleport.
sure, sure, I just think the is part is the heavy part of that... but in any case it doesn't matter, because different use-cases
not at all, the is is a simple recursive walk through the Type hierarchy
Probably something else is overriding the position after it?
looks fine, you don't happen to have a Rigidbody on there as well ?
I do have one. Should I try taking it off?
sure, and the "cast" in that case is what? it basically just allows you to call the methods on the thing that you already know are there because you checked with is... it's not an object conversion of any sort...
yes, you cannot have ChartacterController and Rigidbody on the same object
Oh that did it
had no idea. thanks
unfortunatly not the way it works
if (a is B b)
is executed internally as
if (a is B)
B b = a as B;
and the as will do the Type hierarchy walk again
of course it's not, come on, they're not stupid
bet
yep
rember this is relatively new syntax, it was bolted onto existing code
you can see the IL code in the link I posted above... it's not exactly the same for is B b and as B, but it's almost the same and the isinst check happens once
When i try setting the values of variables in the inpsector that references other GameObjects, it keep saying Type mismatch (this applies to Canvas and CardAnim). However when I do the same to an instance of a prefab, it works fine.
Prefab:
Instance:
you cannot assign scene objects to a prefab
so I have to do it through script?
yes
Hey I'm making an example mod for game "ultrakill", and this is my first mod
Is there a way I can turn "else if(Input.GetKey(KeyCode.something))" into a switch statement?
why it would make literally 0 difference
idk, is there a way to make it work?
also applying deltaTime to addForce is wrong
moving rigidbody in update is even more
you should worry about fixing that if anything..
you dont even need a switch, make arrays of the KeyCodes you want to check and the Vector3 to apply and use a for loop
if(isFacingRight)
{
gameObject.transform.eulerAngles = new Vector3(0, gameObject.transform.eulerAngles.y + 180, 0);
shootBullet.direction = 1f;
}
else
{
gameObject.transform.eulerAngles = new Vector3(0, gameObject.transform.eulerAngles.y - 180, 0);
shootBullet.direction = -1f;
}```
tryinig to make my character flip wtih this simple script
i want to flip the character so everything else flips with him
NO
gameObject.transform.eulerAngles = new Vector3(0, gameObject.transform.eulerAngles.y + 180, 0);
is wrong
gameObject.transform.rotation = Quaternion.Euler(0,180,0) * gameObject.transform.rotation;
don't be surprised, most people never do
u mean quiters?
no, I mean Quaternion math is very complex to understand
i will understand it at some point
I wish you luck, I still struggle at times
or maybe not
i mean, this worked nice for me (2d platformer, i guess they do the same)
if ((moveVector.x > 0) && !facingRight){
facingRight = true;
tr.eulerAngles = new Vector3(0, 0, 0);
}
if ((moveVector.x < 0) && facingRight){
facingRight = false;
tr.eulerAngles = new Vector3(0, 180, 0);
}
but you are probably right
p.s. tr = transform
also my player is always rotating like a tornado
setting Euler angles is fine, it's reading the values and then using them which is wrong
tbh transform.eulerAngles should just not have a get accessor
it works perfectly now thanks guys
i mean it kinda does i still need to set up the camera and stuff
how do i stop the camera from rotating with the player
change your hierarchy
cinemachine
then why ask here when there is #š„ācinemachine
oh
also my bullet is trigger
how do i make it so when it collides whith a wall it breaks
its a trigger bec it passes through the player so if it wasnt a trigger the player would be pushed and the bullet would get destroyed
Add the OnTriggerEnter method on your bullet script
passes through objects
Because it is a trigger
i want it to only pass through player
Should the collision still happen?
you can make colliders ignore each other
how?
do you never look at the docs?
https://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html
first person camera works
controls, kinda work
how do i get the camera and controls to work in sync
w makes the character go where hes looking i mean
move code on character
mouselook
yo uhh guys, what public variable should i make so that i can drag a script into it, like
Public OtherSCript Script;
Script.variable_from_that_script = edit_to_My_choice
something like this if u get my point
Public class, scriptable object or what
if you have
public class MyClass { }
then you would use
public MyClass myClass;
to expose a reference to the inspector
can i get some help because im lost on how to use the rotation and make it affect the forward face
alr gang
any reason not to put CurrentHealth and _uiDocument in the same block? and if so which is better between the class block and Start()
I think you'll find out as you continue writing the code. _uiDocument variable is lost at the end of Start, which is probably not what you want assuming you want to keep reusing it to update the health value.
what would be the point of having _uidocment only visible to the Start method ?
I see, so variables are only usable in the {} block they're in
yes, it's called scope
This is what it says on the tutorial but they might fix it later
absolutely pointless
Well it depends on what they end up doing with it
Ok, it looks like the current implementation is just to show the health that's at the very start of the game
Braindead moment, if I have an object that usually stays inactive in the hierarchy, which method do I use to run a script once every time it's activated?
OnEnable
Thankies.
For a 2d side scroller, imagine you have coins to collect. Player plays the same level with some changes to obstacles when they finish the level(Level restarts). On level one player will have 10 coins to collect, on two 5. The spawn position for level 1 will be determined using where we placed some empty objects at, same goes for level 2 as well. But if player only collects 3 out of the 10 coins on level one, the non collected 7 coins should remain in their position when level 2 loads(Level 2 will also load coins for level 2, so 7+5= 12). How do I store these values?
dont need to store them, just DDOL them
Im not actually a programmer, not sure what that means
Dont Destroy On Load, look it up in the docs
exactly, they can chose to do it themselves by subscribing to the OnBeforeSceneLoad event
Hi. so I have these two lines of code but every time I trigger respawn by pressing R every thing works smoothly than it just freezes this is after the player is killed/turned into a null (followed a tutorial they said it was easier to turn it into a null if you have a better way please indulge me) but when ever I press respawn before the player gets killed the everything works fine and no freezing
sceneOne
public class RespawnPlayer : MonoBehaviour
{
public void Update()
{
if (Input.GetKeyDown(KeyCode.R))
{
SceneManager.LoadScene(3);
Debug.Log("Player has become null and is now respawning");
}
}
}
and
Respawn Scene
public class SceneRespawn : MonoBehaviour
{
void Start()
{
SceneManager.LoadScene(2);
}
}
it might be a dumb question but im following a tutorial and i have a question why does it show error when i try to define the horizontalinput value where i defined the float variable ?
What error?
this
That error is not caused by that code.
you cannot set a value like that in a field initializer
ohhhh im just confused cause i saw some c# tutorials and they tell we can define it with the variable itself but it not working here š
ahh like its just not possible huh
no, field initializers must be a compile time constant
ohh okay so like the value that changes cant be define outside ??
exactly
ahhhhhh okayyy thanks for the help :))
im very new to coding and unity dont mind my dumb self š
np, there is a way to do this but I wont confuse you with it
ohhh yeahh i wont be able keep up haha ima just complete this tuts to get comfortable with everything :)
Why use this instead of just accessing the UIController directly?
It's used to access the static methods and stuff
All the fields and stuff are private by default so
no, it's used to access the NONE static stuff via a static call
because if everything was static you would not be able to set values in the inspector
oh ok
line 63 is UIController.Instance.SetHealthValue(Health / (float)MaxHealth);
uicontroller exists, instance exists, SetHealthValue exists, Health exists, MaxHealth exists
so instance is null
yes, and does this code run BEFORE the other code you posted?
yes, that's awake, so it runs before the game starts
not quite true
the ChangeHealth is used during the game, when you walk into damage
nevermind!
unity visual bug!
the compiler error disappeared when i clicked play
what compiler error? what you posted is a runtime error
I know, you need to stop jumping to incorrect conclusions
previously it said "fix all compiler errors" so i assumed the red mark meant compiler errors
Nope, you cannot enter play mode if you have compiler errors, if you can enter playmode any errors are runtime errors
yeah, i knew something was up as soon as it let me run
how do i make a static public variable also be shown within unity's editor?
Where it can be shown here
cant unfortunately
i don't think static variables can be edited there according to this
You dont, because static variables aren't associated with the instance. It wouldnt really make sense to even show on an instance.
You would need some custom editor script though if you truly wanted to
which makes sense, because each script component is an instance of the class, not the class itself
you can make a scriptable object and a manager that has a static reference to this scriptable object
i feel like it should still be able to be adjusted on the script's inspector menu itself
yeah that would make more sense
Damn because I have this issue where I need to reference an object's transform component but I usually do that by drag and dropping. But since the transform is on another object I can drag and drop that component
either way I usually just have a singleton with a static reference to the singleton
then add stuff to the singleton
Sorry to ask but what is a singleton
only one object can be made for that class
e.g. I have a DialogueManager script, and only one object will have this script
How do i reference an object's component (like rigidbody or transform) without drag and dropping?
GetComponent
a quick beginners guide to GetComponent
Call this on a GameObject to get a specified component
Animator animator = GetComponent<Animator>();
Don't call GetComponent every frame.
void Update() {
GetComponent<Animator>().Play("Walk"); // this is TERRIBLE practice!
}
To get the component of another GameObject(this example uses OnTriggerEnter):
void OnTriggerEnter(Collider other) {
Animator animator = other.gameObject.GetComponent<Animator>();
}
Additionally, be careful of null references. Not every object has the component you're looking for so be diligent
Thanks
Collider is a Component, so the gameObject reference is not required
yea I just wanted to demonstrate that its better to call it on a gameobject
"The name 'playerref' does not exist in the current context", this error popped up when I tried to use the component referred
we dont know what your code looks like
oh sorry
This is a local variable, so, surely, it won't be accessible anywhere outside of the method it's assigned in
The variable should be created outside of the method, and only changed there
So do I add the playerref declaration into the update method?
According to what you're trying to achieve
declare playerref in your class(outside ontriggerenter), then set playerref in ontriggerenter
Not sure how you're going to reference other this way
OnTrigger is only appropriate if you are planning to enter a trigger collider of the object.
If an object spawned at runtime needs a reference to a scene object or other objects spawned at runtime, you probably want https://unity.huh.how/references/simple-dependency-injection
https://unity.huh.how/references/prefabs-referencing-components
Why can this object only accept the player's transform component when it is in the hierachy but not when it's in the assets folder? I just want that everytime this object spawns, this variable is already connected
prefabs cannot reference in-scene objects https://unity.huh.how/references/prefabs-referencing-components
An asset does not belong to a scene therefore it does not exist. You cannot reference an object that does not exist. You need to reference the instance created in the scene (which appears in the hierarchy) . . .
So the alternative?
fill the variable when you instantiate the prefab
read the information on the page?
They sent a link in their response. Did you click and read the page?
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Rendering;
public class NewBehaviourScript : MonoBehaviour
{
public Transform position;
public Vector3 Spawnpoint;
void OnCollisionEnter(Collision collisionInfo){
Debug.Log("you just hit the" + collisionInfo.collider.name);
if (collisionInfo.collider.tag == "Obstacle"){
FindObjectOfType<CubeMovement.Collider_check = true;
FindObjectOfType<GamemanagerScript>().EndGame();
}
}
}
Can anyon explain what do I replace MoveToTargetExample with? Is it transform?
A bit confused
that is not even C# @queen adder
trying to make a first person controller, it works fine, goes in the direction that i look at but i cant go diagonally?
is this a wrong way of doing it?
wait i figured it out
This is a syntax error. You did not correctly input the type when using FindObjectOfType . . .
im setting it to only that direction
how do i make them addup?
+= instead of =
that is what + generally does, yes
my brain stopped working for a split secdon
hey guys can i have a question?
im done so yea
sure, how many fives make 5
not thinking like a dev, you are missing 2 options
No, I will not give you a question; however, you can ask a question (if you dare) . . .
how many more options are there?
š¢
at least 2, in context, many more taken out of context
i have 2 questions but ill let ultimate fusion go first
You don't need to ask to ask, just ask the question . . .
Umm why my rigidbody2D dont have green line like(pic1) like pic2? and the result of those code (in pic 2) is this (pic3) i ve alr code like him but i cant have the result like him?
There is no queue, just have at it. What if his question goes on for hours?
this is called not defining it right?
!ide
absolutely
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
Make sure your IDE is configured. Check the bot for your IDE and follow the link . . .
question is, why does my character fall really slowly?
this one?
By default, fields are marked private if no access modifer is used . . .
no capital B in Rigidbody2D
it doesnt work š¦
Did you check and follow the !ide link?
configure your ide first before asking more questions
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
yes, do either public or private, public just means its visible and configurable in the inspector in unity
i ve installed vs 2022
the purple one
Okay, now follow the link to make sure it's configured with Unity . . .
where link ?
That's only in regards to Unity. public gives outside access to all objects and types . . .
Inside the bot message . . .
umm i used to use vs code to coding the blue one and when i write those codes in the blue one its work š
I have alr done all of that
No prob, I'll send the invoice later . . .
Hello š
Can someone help me understand why my cube keeps going up seemingly infinitely after W is pressed? Thank you š
because you keep adding the force
0 * distanceUp * Time.deltaTime is 0 btw
Either way, never ever use deltaTime in AddForce
ok thank you š
I made this the code but it still goes up seemingly infinitely
Did you perhaps disable gravity in settings?
Is the mass very low?
Nevermind I fixed it š
Yeah I did hahha, thanks for the help š
https://stackoverflow.com/questions/78804205/how-can-i-make-the-counter-from-the-stage-selection-to-go-up-when-touching-an-ob
I guess i will use stack overflow to try and get help from someone there
You should reword that to be more clear. It is almost gibberish.
As you have been told, use generic names.
"How can I increase my counter and have it persist across scenes and runtime"
Absolutely no reason to show the counter (where you write 0/15) or use the word muon or anything like that
Also, they will likely give you the same answers we have. Use singletons in ddol and file writing like playerprefs (they may recommend json or binary instead though)
ohhh no..
If you think we can be harsh, well just prepare yourself for stack overflow....
stack overflow will be savage
Hey, is there an advantage over using an abstract state machines vs. an enum one?
scaleability
I think the post will be simply closed...
Yeah, I was just writing that. It may be closed or just completely ignored
Definitely not gonna get the kind of answer linedol wants though, that is the one thing I do not see happening
i mean what could possibly still being going on?
yesterday u had ur triggers working & you had a singleton instance to call
just add DDOL to the singleton gameobjct
and you'll have ur score thru all scenes
@hushed hinge If it's about making the counter persistent, I remember explaining you this more than 2 months ago #1237752727564582952 message
Time flies
im still trying to figure out what that is
And keep in mind that there's also a disadvantage in using an abstract one vs an enum one - it's way more complicated š
holy sh~t
I'm pretty sure every single person in the server has taken a crack at explaining this to them
no need to be negative, guys š
tons of resources available in search then š
At a certain point, there really, truly, is
I can see an enum one being more advantageous on a small script
yes, if its small use enums
Sometimes, you may use both
my personal rule is "use the simplest thing that handles this week's requirements" š (yes, I did just come up with it, but it gives the main idea)
refactor tommorrow "f*ck you past self"
I have been trying to help them for like 4 or 5 months. We are not being negative. Just realistic
i just realized the extent of it
refactoring is much easier than planning for unknown futures... I've tried that a few times and it ends up in sadness š
i mean ur not wrong
eventually ur hindsight grows
its frustrating.. b/c i feel like he's skipped some fundamentals.. and ofc there seems to be a hella language barrier going on
at this point i would recommend starting from scratch
its only a trigger and a score counter..
hell i'll make a unitypackage and send it to him ** Let me Know if You Want a Unity Package Linedol **
A few days ago I have implemented a player builder functionality, which worked in a single class with enums. Then, I didn't like how messy it was, so I have removed all that and implement a class-based system with a bunch of abstract and non-abstract classes, which requires 20 times more code. Next time I'm going to implement the hardest thing from the start
wdym
huh
got an example of ur setup? i'd like to see the State Changed type functions
you're joking or? š
oh i see it
soo stupid
i always have issues w/ state changed OnStateEnter.. OnStateExit type of stuf
Well, these are options, which can be either selected (e.g. for constantly drawing), or selected while the key is held (e.g. for asynchronously removing the tiles)
enums are easier for me.. b/c i can just put that stuff in teh switch statement before starting any loops or anything
ahh okay..
See #854851968446365696
Both Huh and wdym in the "don't" section.
It looks like this
clean
Well, I still feel like it's too much, because of how little code each class has
public class PlayerBuildDraw : PlayerBuildToggleBase
{
public PlayerBuildDraw(PlayerBuilder target, EventKeyBindings selectBindigns)
: base(target, selectBindigns) { }
public PlayerBuildDraw(PlayerBuilder target, EventKeyBindings selectBindigns,
EventKeyBindings modifyBindings)
: base(target, selectBindigns, modifyBindings) { }
public override PlayerBuildType GetBuildType() => PlayerBuildType.Draw;
public override bool ExecuteModify() =>
Player.TryAddTileWorld(Target.WorldMousePosition);
}
ohh, i cleaned up my folder finally, told ya id eventually get around to it š
Also, as said yesterday, you should get rid of that cSpell extension
is there a way of checking if a collider is triggered
OnTriggerEnter?
i am trying to make a system for keeping track of rpg-style character stats, as well as making a character creator/editor with a GUI. I am feeling seriously bogged down and stuck. would anyone with more experience be willing to look at what I have and critique, give me advice and point me in the right direction?
im sure youll tell me im doing it all wrong and what i have is a complete mess
which would be fine
what does you use canvas or ui toolkit ?
canvas
did you need this in world or only in screen. for your creator you can use ui toolkit
well i was envisioning a character "editor" which is also just what you use in-game when just viewing character status or leveling up whatever
is ui toolkit easier?
im sure my approach is wrong somehow but its driving me nuts
im still getting a feel for how much should be handled by Unity vs C#
if you are a website developer then yes
i write you pn
yeah i heard its similar to that
but i'd just use the default ui
I don't remember
I am just bad at grammar
how can i fix the variables in unity not updating when i change the values of the variables in the script
you cannot, that is intended behaviour
It's not a grammar issue honestly. You need to stop overexplaining
if the vars are public, they will not change in unless they are changed in the editor
Well, it took both of us a few hours, so it's a shame you don't remember everything I've been trying to explain you
I'm sorry
well I do still have that thread we were talking in, I've been looking up in there recently, but I don't know if this was the one
how would I go about changing the texture2D of a gameobject via script?
make a public array of textures for inspector, populate the textures into the inspector then in code where you set the texture, pass in the index of hte array that you want it to use
easier to just swap out materials though
Hey, is there a reason why none of these variables show up in the inspector?
It compiles and runs the states just fine
probably because MovingState and IdleState are not serializable
Can I make them serializable?
sure, add the attribute
Not the attribute in front of currentState, to be clear.
The attribute above the class definition
[System.Serializeable]
Like that?