#💻┃code-beginner
1 messages · Page 537 of 1
...no, just no.
using examples that aren't viable isn't a good way to teach someone an unrelated skill.
Why when I build the game, it's missing a whole script and an image, but works fine in test mode?
it is a viable way to assign something? They will see the error and try to fix it, not just copy code and see that it works and forget about it
it's not viable for static, this-gameobject components
inspector fields should be for parameters for that component. why set components in the inspector if they're never going to change?
you'd have to parse it when reading, or filter it out mentally, and make sure to not accidentally touch them
you'd either have to set up prefabs for everything, or set those components every time you attach that component
if you ever want to add that component at runtime, you'd have to make sure to set all those fields
why not just let the component manage its own, unchanging references?
setting these via inspector is just more work, more stuff to accidentally touch, more stuff to read, obscuring the actual parameters for the component
I use GetComponent in situations where the object I want absolutely must exist on the same object as my component, and where this will never change
I do generally prefer to use a serialized reference
yes if you are using a prefab or if the switch out in runtime/need it on that gameobject then sure use getcomponent, also you'd have to parse it when reading, or filter it out mentally, and make sure to not accidentally touch them? It's literally as easy as dragging and dropping either the component or the gameobject into the fields and just not touch them anymore, that is it. It is not hard to do and is fine for their project to learn the ropes
ah yes i love having to read through 5 components before i can see the stuff i want to actually change
do you not know what "accidentally" means lmao
sure it's not hard to not intentionally touch them
accidentally doesnt' care about what's hard or not
but assigning it on startup makes it impossible to accidentally mess up the reference
how would you accidentally drag and drop a component onto a field and not see that you just did that to the wrong field
that does not make any sense
like i said before, examples of unviable situations aren't good examples
if you use this as an example to "learn the ropes", this would be the pattern going forward
do you think a beginner would have the foresight to not have way too many components and parameters on the same component
you're just increasing the future workload with an example that has much better, actual real use-case examples
like _walkSpeed, maybe focus on that and recommend setting that via the inspector, instead of the thing that gets no benefit and only has downsides by being in the inspector
going fast, being a beginner and not recognizing it, having identical gameobject names
it's really not that hard to imagine a scenario
you gotta remember these are not people with experience
yes if you are using a prefab or if the switch out in runtime/need it on that gameobject then sure use getcomponent
these are not the situations i mentioned, btw.
im saying that, if you use your method of setting stuff in the inspector, you can't reuse the component without going through the process of dragging the same gameobject in every component field, and making sure not to drag the wrong one in
or you'd have to make a prefab, just to reuse a component
that just doesn't make sense
setting stuff in the inspector does not have any reasonable upsides, and it has quite a few significant downsides
ive made my points, we're going in circles, im done here
not a code question, see #💻┃unity-talk
Hello. I come with a new problem: I made the character movement using a character controller. The question is: how do I make the character "stick" to the ground? because when I press play, the character is levitating
make the collider smaller
or just.. move it, relative to the model
Note that there is a small "skin" that extends past the visible collider
so you might need to move its center a little higher than you think
something like that ?
if it is touching the ground how you would like then sure
I am still new with using character controller, but is there a way to "snap" the character to the ground or something?
IK could do that
or a simple raycast
the brute force answer:
move the character down super far
...that might cause you slide off to the side, actually
I'm pretty sure they're talking about the visuals matching perfectly with the collider
ah, true. clarify pls
if they want no feet sliding, IK could do that
that, but I am also asking if there is a snap function, like in blender for example
oh, yeah, when moving things around in the scene view?
IK?
Yes but not necessarily for what you're thinking/talking about
https://docs.unity3d.com/Manual/GridSnapping.html
Inverse Kinematics
inverse kinematics would be appropriate for making the feet rest firmly on the ground
Also, if you hold shift + ctrl while moving an object, it will snap onto colliders
This may be what you're thinking of
if you want a runtime snap, you could use a raycast like murado said or just stick the feet to the ground using IK
but IK isn't used with rigidbody?
inverse kinematics is an animation thing
IK has no connection to RB or CC
oh, I see
If you're strictly asking "how do I snap an object onto the ground in the scene view?", then see here
also, see how the behavior varies when using "Center" mode vs. "Pivot" mode. I just noticed that it matters!
that helped a lot
now back to remaking the animations work again xD
also, does this allways appear because I have both the old and new input system enabled in the project?
No, that is unrelated.
It is one hell of a legacy warning though
a long time ago, back when giants roamed the earth, Component had some properties on it like camera and rigidbody
basically equivalent to calling GetComponent
These properties were deprecated ages ago and don't work in builds anymore
But they still exist in the editor, so you still get warnings when you declare a member with the same name
ah, I see
You can tell the compiler you meant to do this by adding the new keyword. But I'm pretty sure this then causes complaints during builds (because the properties don't exist in a build)
I was kind of hoping they'd make the enormous breaking change of deleting these damn things in Unity 6
ah well
[SerializeField] private Transform camera;
that's the line
I either use another name or ignore the warning
also you're going to be told to use Cinemachine in about...3 seconds
😄
(it's cool, use it!)
the developers have added features I pined for on the cinemachine forum
yeah, I want to use cinemachine, but either I am not good enough or I am doing something wrong sometimes
especially when I want to use freelook
i cant make a function in a function right
welp, I changed back to cinemachine and somehow I got it right
like the freelook is working as I want now
how to remove black from trees
isn't that a texture error?
idk
certainly not a code problem
oh you think
no, I know. So why post in a code channel
where should i post it
Make it transparent
yeah i did it thx
is there some better way of handling UI references to a DDOL script? it was causing issues for me so I just disabled DDOL and put the script in both scenes and manually assigned it, but I feel like there is something better I could do
Is this a singleton? If this DDOL'd component always exists (and there is never more than one of it), then adding a way to statically access it would be fine
for example, I have a GameController component that bootstraps the game and is responsible for switching between modes (title screen, main menu, gameplay)
It lives in DontDestroyOnLoad forever
dont reference it directly, just reference it by the static class call
you may need to change execution ordering if it is spawned in the same scene though
You can also handle execution ordering by having a load scene and throwing all your DDOL managers onto that
(and I access it through GameController.Instance, which is static)
that part is fine, I just meant specifically in the case of "outside of code" (unity UI for example)
oh it may have been that as well
I didn't consider that
project settings there's an execution ordering tab
That would not affect your ability to store a reference to the DDOL'd component
you won't be able to serialize references to whatever this thing is
would I have to assign the buttons in awake/start when the scene is first loaded then?
Explain what you're actually doing here. What is this DDOL'd object?
similar to yours, a SceneManager of sorts - loads scenes, reloads current scene
okay, so you have some UI that lives in individual game scenes and that needs to be able to talk to the SceneManager
yes (play button for instance)
Create a new component and put it on the UI object
Have the buttons call methods on this component
and then have that component find the scene manager and call whatever methods are needed on it
by component you mean a new script right?
a new script file that contains a class that inherits from MonoBehaviour
that's how you define a new kind of component
ah okay i think i understand what you mean now
(i don't like to use "script" for anything but the actual script files)
Button > NewComponent > find SceneManager
yeah i get that, just had to make sure since im pretty bad at remembering all the terminologies for everything
This avoids needing any direct references between the UI and your SceneManager object
Im working on a 2d game. When i shoot (right click) there come a bullet and it does damage and all but the speed is the problem. If click close to the firepoint the bullet goes slower then when i click futher away. Anyone knows how to fix this? (i want them to go the same speed reguardless of the distance of where you click)
Sounds like you're doing something like this
Vector2 shootDir = clickPoint - playerPosition;
bullet.velocity = shootDir;
The code has too many characters to past here but i can send a ss of what i currently have
okay, so you correctly normalize that vector before using it
Ah, but there is one issue
You do these two things:
- Normalize the vector
- Set the Z component to zero
What if the Z component was very large? That means most of the vector's length is pointing in the Z direction
So when you normalize it and then remove that Z component, the resulting vector is very short
you want direction to have a length of 1
but you're normalizing it before you get rid of the Z component, so the length is no longer 1
Ok thanks ill try that
you'll try what?
Bruhh i have no idea what im doing rn so... plz help
(well, actually, nothing will really change -- the Z component gets thrown out when you set the velocity)
void Shoot()
{
// Bereken de richting van de muis naar het afvuurpunt
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector3 direction = (mousePos - firePoint.position).normalized;
direction.z = 0;
for (int i = 0; i < numberOfPellets; i++)
{
float spread = Random.Range(-spreadAngle, spreadAngle);
Vector3 spreadDirection = Quaternion.Euler(0, 0, spread) * direction;
GameObject bullet = Instantiate(bulletPrefab, firePoint.position, Quaternion.identity);
Rigidbody2D bulletRb = bullet.GetComponent<Rigidbody2D>();
bulletRb.velocity = spreadDirection * shotSpeed;
BulletScript bulletScript = bullet.GetComponent<BulletScript>();
bulletScript.maxReach = maxReach;
bulletScript.damage = damage;
}
}
}
idk what to do at this point
stop and think about what these two steps are doing
let's break it down into three steps...
Vector3 direction = (mousePos - firePoint.position);
direction = direction.normalized;
normalized.z = 0;
ok yes
tell me what each of these steps does
it calculates where to shoot and normalizes the diractoin?
no, I want you to explain what each line is doing and why it's there
Vector3 direction = (mousePos - firePoint.position);
calculates the direction from the firePoint to the mouse position
direction = direction.normalized;
normalizes the direction vector so it does something idk bout that accutally just found it online
!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 you need to figure out what this "normalized" thing actually means
right now it's just a magic incantation
and it's not working!
see the link dec_ves posted
ye ik its not working but idk how to fix it
because you don't know why you're doing it
A vector has a direction (where it's pointing) and a magnitude (how far it goes).
Vector3 shootVec = new Vector3(100, 0, 0);
This vector points to the right and has a magnitude of 100.
If I set my bullet's velocity to shootVec, it would start flying at 100 meters per second to the right.
ok ye i understand
Vector3 shootVec = mousePos - firePoint.position
The further apart mousePos and firePoint.position are, the longer shootVec is
So if you just used shootVec without any further work, your bullets would fly twice as fast if you clicked twice as far away.
That's obviously wrong.
so normalization helps with this
by keeping the same direction whilst making the magnitude 1, which then can be multiplied using the fundamentals of multiplication
ye i tried but apperenlty i did it wrong ig
Vector3 shootVec = mousePos - firePoint.position;
Vector3 vec1 = shootVec * 10;
Vector3 vec2 = shootVec.normalized * 10;
The magnitude of vec1 depends on how far apart the two points are.
The magnitude of vec2 is always exactly 10
So that's why we normalize here. We only care about a direction between two points. We don't care about how far apart the two points are.
yes
But there's a second problem -- mousePos and firePoint.position can have different Z components.
mousePos is probably at Z=-10 or something, where the camera is located
frick... yes
Vector3 shootVec = new Vector3(1, 1, -10);
If you normalize this vector, its X and Y values are going to be very small
The vector barely points in the X or Y directions.
It mostly just points in the -Z direction
Therefore...
Vector3 shootVec = new Vector3(1, 1, -10); // magnitude is a little more than 10
shootVec = shootVec.normalized; // magnitude is now 1
shootVec.z = 0; // magnitude is now almost 0
That's your problem.
ok i kinda understand now
ok i understand what you just explained but... what do i need to remove and add to my code?
here's a visual example. this vector mostly points straight up -- if I then get rid of the up-and-down part, the resulting vector is much shorter!
yeye i understood that part and all
so what should I do if I don't care about a vector's magnitude, and just want a direction..?
remove the vectors magnitude?
which you can do by...
idk just plz help, i dont need a whole explaination rn
Well, you just got one and it told you what the answer is
you already know how to do this because you've already done it!
i feel really stupid rn ):
scroll up
im new to coding alr go easy on me plz
So, since a vector is a direction and a magnitude, and you want the vector without the magnitude, what is a way to get the direction of a vector
what if i just use a vector2 instead of vector3?
Vector2s still have direction and magnitude
you might accidentally solve the problem by doing that
again: the problem is that, after doing this:
shootVec.z = 0;
shootVec's magnitude is no longer 1
but we want it to be exactly 1, so that we get a consistent speed for our bullet
ye i mean i understand that whole think about magnitude but idk how to apply it
you already did it
i havent changed my code since the start of this conversaion
look at your code
what there makes the magnitude of a vector 1 whilst keeping the direction
Hint: You just got an extensive explanation as to what this function does
So, what was the name of the function Fen was explaining earlier?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Correct. shootVec.normalized gives you a vector that points in the same direction as shootVec, but with a magnitude of exactly 1.
let me provide a more obvious example
shootVec = // whatever
shootVec = shootVec.normalized;
shootVec.z = 999999999;
shootVec's magnitude is now...not 1
it needs to be normalized again.
coming back to the sensible example:
shootVec = // whatever
shootVec = shootVec.normalized;
shootVec.z = 0;
shootVec = shootVec.normalized;
now we have a vector that:
- only points in the X and Y directions
- has a length of exactly 1
The first normalization is pointless -- we don't care about the value of shootVec after normalizing it the first time -- so it can be removed
well, given that I directly gave you the correct code, I'd think you're there already..
bruh ):
I know this isn't related to unity but for some reason, the circle is respawning instead of falling down. Here's the code: https://pastecode.io/s/3g7kqcox
This is a Unity server
I know, but people in other servers weren't saying anything.
okay, but this is still a Unity server
This looks like web-page javascript, which is not known for having any sort of physics engine
wondering how we're supposed to know what this is, what it's written in, or how we'd even know to help . . .
Hey! I got these venom thingies in my game and I want to do two things: First, make a checkpoint in the level in a certain point and second, when colliding with the venom, it sends you to that checkpoint. I'm a beginner to coding and I don't know how to do this, would appreciate some help/guidance!
I don't have a life or HP system neither do I want to place one. Just like... it transports you to the checkpoint. Like you have to avoid it to progress
That's my design logic
Please stop asking non-Unity related questions in this server. Thanks.
Have you gone over any tutorials for stuff like coin collecting? It's probably a good idea to learn first then you will have an idea how you can interact with other gameobjects
because you can use that same concept to say, add flags (checkpoints) throughout your level which if you come into contact with will flag your most previous location
Actually, if you have the venom/death logic working already then you should probably have an idea how to do contacts
Yes! I've done coin collecting a few times before, but in 3D mostly
How about a GameManager and using singletons? That would make this pretty quick
What is a singleton, if I may ask?
They're (semi) static classes that can live on the scene
but two ways I would resolve this:
- Do it similar to the coins such that if you come into contact with a check point, then update the player's last known checkpoint location on the character itself (much like incrementing your coin counter)
- Instead of writing that value on the character instance, communicate to the GameManager and set it there
Oooh okay, I'm starting to get it now!
I think the second one is a bit more viable for me at the moment
Thank you so much for helping me understand!
https://paste.myst.rs/t3xh2zap
guys i'm a bit confused. Why the game stops until the coroutine is ended? I can't see the movement, it's just like a teleport as now....
a powerful website for storing and sharing text and code snippets. completely free and open source.
Your while loop there is probably locking the main thread. You'll want to yield inside of it
oh yeah it worked!
yeah, careful working with while loops
Mario-like swimming help, ad general control issues
how can we possible know that without looking at the code / setup
if you're not using transitions then you have to better match how you switch back to the idle clip
Earlier I asked about projecting a png from a point and was recommended this: https://docs.unity3d.com/Manual/prepare-materials-projection.html
But I'm on 2021.3.39f1 and the legacy standard assets are deprecated and no longer available.
I can't use URP due to issues with other shaders on unreplaceable assets...
You are bringing up three different issues. What exactly is your problem with tue suggested link, which is working in all recent versions from what I can tell in the docs.
Is it good to put every reference slot to public, like "public rigidbody2D rb" instead of private ? Is there a point to make a reference private ?
This is to prevent other scripts or users to access it if you dont want it accessible. Also preventing values to be overriden in inspector when set to public can be a good use of private
You should get used to making all of the fields private. Aside from maybe in structs.
Is there a reason to make things unaccessible ?
encapsulation makes separation of concerns clearer, and prevents accidental external modification
Imagine you never closed a door to your house or windows and let anyone get in freely and take what they want.
Sorry but I don't see how it's applied in coding
i have a program snippet her https://hatebin.com/llszcphjaz and i want to increase the en array to have the same length as the colliders array.
Well, here's a better analogy. Imagine scripts being departments in a huge company or factory. You don't want people from other departments to enter freely in your department and interfere with your work, do you? Scripts(or classes) are these separate departments. They all do their own thing and only cooperate with each other using the official channels and rules.
so you need to implement the code I showed you but do it properly. Dont just copy/paste
By making a field public, you're basically allowing anyone to get in there and do with it whatever they want.
so not a local variable
of course not. en is not a local variable so why create a new one?
ok
I saw some people use m_name instead of just name when assign variables, is there a reason to this ?
like int m_score instead of int score;
old C and C++ code convention
That's just a naming convention. They use it to denote that the variable is a private field.
these things are from pre IDE days and totally irrelevant today
It depends on the conventions in your project or company. There are many that still conform to them. Especially in C++
works now. thanks
One very important thing to realize here: these are all for the developers to make the development process smoother. Private/public is your way of denoting what values are allowed to be edited externally to the script. There is no change in the actual game logic or what the user sees when playing the game.
What you were told above by others is correct but I cant imagine youd really understand the terms used or analogies much as a beginner. It's something you'll start to understand more with time. A lot of the time, you dont want other scripts to be able to edit the variables
Thanks ! your answer helps alot
It's also useful to do that because you know that whenever you type m_, you'll get every field you're looking for. Your IDE won't show you any gibberish in the list of symbols it will prompt you
Probably nowadays indeed
hello, since I'm trying everything possible, I would like to know if I wrote this wrong. For who doesn't know the issue I'm facing, since I updated from Unity 6000.0.24f1 to 6000.0.30f1, I got into Safe Mode and got these errors. In the 24f1 version, these are not counted as errors, but here these are. Also, today I noticed that other scripts (like the one that manages the player) are like disabled? (in Inspector, they are signed as (Script) and have less opacity, they doesn't even show the public values I used to change).
This is one of the errors that the Unity console displays:
Asets\Scripts\GameManager.cs(22,12): error CS0246: The type or namespace name 'TextMeshProUGUI' csould not be found (are you missing a using directive or an assembly reference?)
Assets\Scripts\AudioManager.cs(11,12): error CS0246: The type or namespace name 'Button' could not be found (are you missing a using directive or an assembly reference?)
how do i add an onclick object and function through script
Try deleting your Library folder and having Unity regenerate it
thanks, but I've already done this, I've tried even deleting these and the upm folder and regenerate the project
there aren't even new updates of packages
in package manager everything seems fine too
you can see TMPro is underlined. In VS open the solution Explorer. then open the References section of Assembly-CSharp and screenshot that
fixed this and now i got a new problem >:/
Check the button.onclick documentation
ya i checked it and the problem is now fixed im gonna look into the new problem i hope it is easy
so I decided to make a sync rotation animation and it kinda work but kinda not
transform.localRotation = Quaternion.Lerp(Quaternion.Euler(0, 0, 0), Quaternion.Euler(0, 360, 0), Mathf.Repeat(Time.unscaledTime * lootSpinSpeed, 1));
I can make it work by making it two lerps
the question I want to ask if there are better ways to do that
or should I even do that or making a "rotation manager" object with a list of stuff to rotate is a better idea
I guess there is also a way to make it a shader? but I... hesitate to touch shaders
So there is obviously a problem with your .csproj file.
Close your project and in the project folder delete the .sln and .csproj files. then open the project to regenerate them
ok I'll try thank you
ok so problem is still here sadly. I also noticed that in package manager, if I try to search textmeshpro in registry, it doesn't show up
can you post the contents of the Assembly-CSharp.csproj to a paste site
sure
Is there any way to make an array vary in length depending on a number of inputs, for example? In c# you have to define the length of the array, but I come from python where you don't have to define the length of the array beforehand, and the length of the array changes automatically.
that's... a list
use a List rather than an Array
thanks a lot dude
uhm... which website can I use to share it? Or can I just send the .csproj file here?
!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.
ignore gdl.space
Say I want my obstacles to disappear after reaching a location, is OnTriggerEnter or an if (reaching position) { Destroy()} in Update better in terms of terms of optimization ?
Also is collision detection has its own interval or it runs with fixedUpdate ?
neither of those options sounds bad optimization wise for me assuming there are few obstacles
for some reason VS is having a problem loading dlls from the Library/ScriptAssemblies folder.
check to see this this file
Library\ScriptAssemblies\Unity.2D.Tilemap.Editor.dll
actually exists in your project
nah
I do see one problem although I have no idea how to fix it
the project has this
<TargetFrameworkVersion>v4.7.1</TargetFrameworkVersion>
targeting .NetFrameWork 4.7.1 but all of the references are targeting .Net Standard 2.1
that's weird, in Player settings I did change it to .Net Standard 2.1
optimization of what ? your question is vague
Destroying object doesn't matter where you do it, the important worry would be Instantiate and Destroying the same objects. That creates constant garbage
btw so, is this a visual studio issue? Maybe triyng to remove it from external tools and adding it again fixes the issue?
does it even matter to this context?
FixedUpdate runs in sync with the physics loop.
https://docs.unity3d.com/6000.0/Documentation/Manual/execution-order.html
it's about how cost efficeint keeping a trigger collider on the scene vs doing update distance checks
if they are instantiating/destroying it matters
Where can I get nametag?
nametag?
it's getting destroyed both casese I believe
wdym both cases. I'm saying destroying a gameobject doesn't matter where its done, there is no optimization benefit there where its done
i mean, you can create a text object and staple it to an object...
this is a very confusing question
My troll detector is tingling a bit but it's not certain
is this roblox ? i'm confused what are we looking at
Where is products? This is Unity Systems profucts?
okay but the question was about what is better to do a distance check or leave a collider
well one requires a rigidbody which has its own expense than simple distance check, if the object already got a rigidbody then yeah trigger is probably a bit better
what is a UnitySystems product? no one knows what that is
wtch
trigger would eat up some performance from sheer being there tho?
no idea if it's worse than having one gameObject running a constant distance check
Spitballing time: I bet a distance check would be marginally faster here
if it already has rigidbody then Trigger is already part of the Sweeps or whatever its doing in the bg for collision/trigger detection for rigidbodies
How many of these objects are we talking? @real thunder
The physics system will do a better job of keeping track of lots of objects that can all collide with each other
yeah I have no idea because the topicstarter didn't state
original poster is @final sluice
#💻┃code-beginner message
Ah it wasnt you
I am getting curious myself
I'm also gonna guess that using a squared distance check would be faster
If it's just one object or a few objects then I wouldn't even bother thinking about it
If it's several, I would probably profile it
I always check squares but I wonder if I should start not giving a shit cause cpus these days are nice
if it already got rigidbody id stay stick to the trigger msgs since you already have the cost of rb / physics running in the physics scene
alright sorry for bumping but
how would you make a synced rotation animation for random coins and such?
you want all coins sync
use a main script/object to loop through all coins for rotation ? or are u asking something else
Explain what you're actually trying to accomplish
Oh, I get it
I was overcomplicating it in my head :p
All you need to do is ensure that each coin is at the same rotation at the same time. Consider something like this...
void Update() {
transform.rotation = Quaternion.AngleAxis(Time.time * 45, Vector3.up);
}
Everything that has this component on it will have the same rotation at the same time.
since they're directly computing a rotation from the current time
(instead of, say, doing...)
Doesn't hurt to use sqr when possible 🤷♂️ But yeah I heard that they can be almost the same
putting an Update loop in each coin tho 😬
transform.rotation *= Quaternion.AngleAxis(45 * Time.deltaTime, Vector3.up);
oh that's really better than lerp
it's object-oriented, baby!
If you want to be really clever, do it in the vertex shader 😉
if you have 200 coins now you got 200 calls into the C++ backend which may not be ideal, I usually mass rotate them with 1 script. Blogpost from unity left me scarred
guess what happens every single time you set transform.rotation
or what happens every time you access any Unity property
I'd like to know 😛
Wouldn't mass rotating them make you also call C++ code 200+ times?
yeah I stated in the start that I am aware of the option of making a shader or a rotation manager object doing that
Most of the common unity object properties are C++ side
[sound of a car crash]
yeah but isn't Update loop more "heavy" or am misunderstanding the unity blog post i read?
I'd be glad to know I worried for no reason xD
I would expect it to be slightly slower to run 200 Update methods instead of just running a single one that iterates over all of your coins
well I have heard that each update call eats some performance even if it's empty
correct
it still has to invoke the method
I think the Update thing may be outdated... I had a much higher number of updates than that, switched to doing it in single Update and it had close to 0 impact (think 2k objects)
the other option would be to make a manager with a list where I put and remove coins from each time tho (no, I am lazy making it pooled)
would it be much better
it was a blogspot. I gotta find it again but wasnt too long ago
honestly I don't really care about small overheads
small things add up, thats the thing
yeah but I am making a small shitty game where it's not much things which may be adding up...
and depends on the platform - mobile/ VR are going to be affected by them much sooner than PC
but yeah never let creativity / progress suffer because of pre-mature optimizations
perhaps, perhaps... I've seen it on a Unite talk years ago, and that's why I tried it, but it really had no meaningful impact for 2k objects for me 🤷♂️ there's always a chance I did it stupidly, but hey 😄
https://unity.com/blog/games/optimize-your-mobile-game-performance-tips-on-profiling-memory-and-code-architecture-from
I think this? but there was a PDF too
You should do whatever makes the most sense to you first
so that your game doesn't make you want to die
I get the whole "premature optimization" thing but I also like to do things right from the get go so that I don't have 1000 small things to optimize later on when they start adding up
I have watched a vid where a dud was like hey lets super optimize your game and make all updates be called by one god entity and make sure to add methods there spawning things and removing despawning things
Let's fight!
good point
and... that does not make many sense
At that point, you are basically just reimplementing Unity's update loop
Now, I actually do something a lot like this in my game
But this is because I want to have explicit control over exactly which order things run in
making your own Tick is also viable.
my entities have modules, and modules can have child modules
the entity ticks all of its modules that don't have parents, and then those modules tick their children
I have modifiet script running order to make sure one godish update always run first
I hate myself doing that
I use that module pattern so much in my games
Ended up making a snippet for it in VSCode
Minimize code that runs every frame
Consider whether code must run every frame. Move unnecessary logic out of Update, LateUpdate, and FixedUpdate. These event functions are convenient places to put code that must update every frame, while extracting any logic that does not need to update with that frequency. Whenever possible, only execute logic when things change.
If you do need to use Update, consider running the code every n frames. This is one way to apply time slicing, a common technique of distributing a heavy workload across multiple frames. In this example, we run the ExampleExpensiveFunction once every three frames:
we've got so many kinds of ticks!
speaking of the profiler most if not all lag I ever saw are caused either by rendering or animation
that's good in cases when you know something's gonna be a problem or when you can easily do the optimized thing without losing time / readability / etc.
problem is that a lot of people optimize randomly making code worse without ever profiling, because someone on the internet said something's better than something maybe kinda
bonus points for when the resulting code runs slower
yes people ask about coding optmization and forget this is probably the #1 perfomance killer is the visuals lol
the #1 performance killer is YOU NEVER FINISH YOUR GAME
Yeah, for sure. The stuff that I know to optimize just comes from previous experiences
not me, spending all of yesterday trying a redesign that turned out to make no sense
well, realizing it was a trash to begin with and doing something else is valid
or am I coping?
What happens in PerformTeardown? 👀
brek it
I...don't remember why I didn't just make Teardown public. That's how Init works.
that's perfectly reasonable, imo... problem is when you lose time writing the perfect code and after 3 months of code perfectionism, you finally run it and realize it sucks as a game, and all the code will be thrown away! 😄
hence the - make it work first, you can optimize later if you care
Oh, I think I was planning to make sure the teardown is valid before calling Teardown
(e.g. no double-teardown)
Making PerformTeardown non-virtual ensures that this behavior is kept by all modules
maybe
i forgor
by the way at some point I realized that if at the same frame alot of collisions or other stuff happened, I might be wanting to first check what happened overall and only then react
does that makes sense?
like I am getting all OnCollisionEnter thingies making events out of them and each fixedupdate if there are any I run through them first and then react to each
does that makes sense?
not event events, I mean I making structs
which are kidna like events to handle
I guess that could be useful if you want to, say, spawn no more than 10 particle effects at once
(and also not just spawn them on the first 10 collisions)
Oh yeah, I have done something like that. I gathered a big list of all possible places to play a sound, and then randomly picked a few to play one shots from
I did that to configure the ragdoll of dying enemies properly
Makes sense if I get what you mean.
Let's say you have two players that shoot each other at the same time. If you don't consider multiple collisions at once, the first shooter will win the game even though they both die at the same frame
And at that point it's basically random, based on execution order
Or are you talking bout something else
I ve heard valve made it consistenly that the player who joined last is the one who dies this situation
somehow
That makes sense from the programming perspective, the player was added to the player list last so its shooting logic gets ran last
I did that to let's say I have raycast shooting shotgun and it killed the enemy where 7 pellets killx and 3 are overkill
and I want to properly give a ragdoll the dying impulse
if it was independent bullets that would be kinda... lame and inconsistent
but each LateUpdate enemy checks all hits he took and if he is dying he goes through all of them again to get the impulse
That reminds me, I gotta do some special logic for my shotgun pellets. No point in playing 8 sounds and 8 blood particles at once if they hit the same spot...
I didn't figure out anything better than making each hit play a sound but more quiet ><
Gonna probably give them some shared ID and add some distance checks to avoid too much clutter
yeah I should ve do something like that
I kind of do that, each projectile has a "caliber" parameter where (roughly) 0 = shotgun pellet, 0.5 = pistol bullet, 1 = medium rifle bullet, 2 = sniper bullet etc.
And that parameter controls the audio in FMOD and the scale of the VFX and bullet decals
Yeah, just edited that in
how do you orient them?
Basic stuff, raycast hit's normal
but what about edgecases
like literally hitting an edge
Not sure if i handle that case atm
It could be fixed by using spherecasts to get a more smoothed normal
But that feels a bit expensive
Maybe I could do it for hits closer to cam
I have spent several days making a code which shoots like 12 raycasts out of the hit point to feel the geometry and accordingly turn the decal
Maybe try a single spherecast instead? It should give decent normals on sharp edges
I will look into it next time I make fps
Like hitting a corner like this should give you an average normal (yellow)
I guess this is the issue you are talking about?
I wonder why did I never find anything about spherecasting while googling how to properly orient a decal
this is one of the cases, yes
worst case is hitting a corner
True
or a.. reversed corner let's say
Apparently I am just relying on the angle fade on the decal to basically just hide decals at bad angles
Just fades out towards the corner
yeah I also didn't knew I could do that or there were no such thing on URP decal
also urp decals are really horrible in terms of making them pooled
they have GPU instancing, they are pretty performant already
by experimenting I found out that the only no alloc way to hide them seemed to be manually setting their size to 0 0
neither scaling to zero or disabling them worked iirc
Hmm.. I gotta investigate if HDRP decals have that issue. Never really thought of it
https://imgur.com/coUp0bL
yep that's really alot of effor about making such ugly decal looking better in such an ugly game
it shoots raycasts to the sides and then either forward or backwards to feel where the bullet hit
And you get the average normal from that?
You could fire a few raycasts and look at how quickly the normals are changing
If the change is dramatic, then do a spherecast or perform more raycasts to get a better average normal
kind of like looking at ddx in a shader
wish I knew anything about shaders
well more than sheer basics
at this point this place seems to me the pinnacle of getting info about making the game out of all
wonder if it is
ddx(...) gives you the derivative of something -- pixels are processed in 2x2 groups, which is where the derivative comes from
so ddx(i.normal) tells you how quickly the normal is changing across pixels, for example
very nifty
unity discussions are not looking very helpful if your question is not trivial, same for google
i've gotten pretty good results just googling my shader questions
which takes me to a Unity Forums link, which redirects me to Discussions
it's complicated, googling most stuff giving me a proper answer, sometimes, however...
sometimes there are alot of answers about something close to my problem but not quite and I can't find stuff about the exact thing
sometimes there is almost nothing and if I ask on forums there are dozens of views but zero answers for weeks and eternity presumably
You often likely to be unable to find solutions for the exact thing you're looking for. What you need to get good at is find things close and extrapolating from there how to sort your thing out
yeah I did this raycast thingie but if I knew about spherecast...
read the docs
Reading the docs for raycast would take you to Physics.Raycast -> Physics is a link -> click and read the other properties/ methods -> SphereCast is present
at some point you just gotta' thumb through the manual, yeah
sometimes I just look at random autocomplete suggestions from my IDE
I don't think reading the docs would help me to get the idea how to orient decals
Like, I was aware that spherecast exists, but it was stated as
"This is useful when a Raycast does not give enough precision, because you want to find out if an object of a specific size, such as a character, will be able to move somewhere without colliding with anything on the way"
getting an average normal is not what I would expect from spherecast, I was expecting it to return the only one normal of the exact place it collides
I did some raycast/spherecast profiling and in a medium complexity scene spherecasts are around ~3x the cost of a single raycast
i was profiling this at one point
i was trying using either a grid of raycasts or one spherecast
i wound up doing neither 💥
Found this tester thing i made some times ago
Idea was to find out when it becomes feasible to use RaycastCommands
I ended up testing NavMesh raycasts, spherecasts etc.
Turned out that NavMesh.Raycast is more expensive than I thought
I use RaycastCommand for my vision system
all of my entities make requests to a vision system, and then it runs a big blob of raycasts
the results get sent out on the next frame
Same here, although I instantly complete the command, I should definitely give it a frame to complete
You won't get full parallelism there
Anything that needs to change the physics scene will stall until the command completes
But it can still help
Yeah It's not optimal
I wonder if I should wait to dispatch the command until rendering is happening...
Half of the implementation is missing
Oh no it's Nitpicky Optimization Time
bring out the scene with 1000 "vision benchmarker" entities
i don't like how this makes it look like a raycast command that performs 200 raycasts is 3x slower than just doing the raycasts

It is slower, but that's completing the command instantly
So not really a fair comparison :P
oh hey, it might actually be completing in time
How many raycasts do you perform on average?
i...removed the thing that tells me how many i'm performing here
hang on
So that's 833 raycasts
I threw 50 "vision benchmarker" entities into a room
each one is trying to look at all of the other entities
it's also timesliced so that only a third of the entities get vision updates per frame
Normally, each entity has several "vision targets", so there are more raycasts
it also shoots rays at light sources so that it can figure out how bright the environment around itself and its target is, but this scene has no realtime lights
also i'm doing 833 spherecasts for uh
why am i doing spherecasts
i thought i turned those off

Yeah I'm thinking of using the same raycastcommand batch for light checks too
Actually I could technically cramp most of my raycasts in the game into one command
📃 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.
here's my silly little light measuring system https://paste.ofcode.org/XMLketcLQz96a975GhmjCs
It's designed for physically accurate lighting in the HDRP
(i love having real light units. what the hell is "0.5 intensity"?)
I haven't bother with mobs interacting with mobs but I can't wait to have the geometrically worsening performance
yeag
Hello, is there a way so that each gameObject that accesses this prefab it has its own version of it and doesnt change it for the other gameObjects
like in this situation i have cities and they each access this building prefab and lets say upgrade its level i want it so that it upgrades for only one city and the others dont
don't modify the prefab
you need to instantiate the prefab and assign it to the GameObject . . .
alright i will do that
and see if it works
instantiating the prefab will create a separate instance. that instance is a copy of the prefab; you can change what ever you want on it . . .
ok thank you
Hi friends, how are you? I have an issue with my Scriptable object and not being able to fix it for some time. Basically I created a small system to spawn enemies and create waves in a mora controllable way to change it on the inspector. The problem here is that, if I change the number of waves from 1 to 100 for example, it works. but if I decide to change lets imagine wave 10 or any wave removing enemies or changing even the prefabs of the enemy that will spawn, sometimes it mess up. and during the game its spawned less or more and when spawed more the object sopawned is not recognized by the player to shoot. Shouldnt it update or save automatically when I do changes there? It only happens if after setting up the number of waves I try to add a new element to add a dif enemy in a random wave. Anyways it is not 100% that will bug but its often.. the thiong is if I have 1 wave and increase the amount to whatever number it works perfectly.. if I edit one of the waves it might woirk but sometimes dont.. like if it mess or dont save or. doesnt make sense.
how doesnt this work
I have zero clue what CopiedBuildingTypes is
and you have not provided the error message
this makes it very hard to give you an answer
That link does NOT work anymore. It says to use the Projector/Light or Projector/Multiply shaders which are NOT built into 2021, and the standard assets download it links to gives Unfortunately, Standard Assets 2018.4 | Check out Starter Assets: First Person & Third Person is no longer available
when you show a red squiggly line, at the very least show the error message that it says..
presumably InstantiatedBuilding is not same type asCopiedBuildingTypes contains (assuming thats even a list and not an array)
hm, yeah, and it doesn't look like the new "Starter Assets" packages include projector shaders
Fortunately, the sahder is remarkably trivial
hmm, i'm trying to use this shader in a Projector and i'm getting weird results
the projected image is appearing on every single object that the projector hits like this
(i threw this into a VRChat project, so this is Unity 2022.3.22f1)
Yeah same thing on mine
It's just overriding the texture of anything it touches
my floor is a single massively stretched out crosshair lmao
I think the projector is failing to set the necessary properties on the material
The shader is suppoesd to use a matrix in a property called _Projector
but if I remove that line, the result is identical
As an alternative, you could just use a light with a cookie
Projectors let you do more complex blending (e.g. darkening a surface)
If you're fine with just making the surface brighter, create a spotlight and give it a cookie
... I'm literally just projecting a laser light in the shape of a crosshair
you'll need to set your cookie texture to clamp, not repeat
see the texture importer settings for that
(otherwise you get very wacky results)
oops
Perfect! That was so much easier, tyty.
Because there's an error, presumably.
i'll have to remember that Projector just..doesn't project. huh.
I mostly do HDRP and URP, so I hadn't used it myself yet
Well you're the one who finally managed to help me out so tysm
okay i got a couple things working
- i got an inventory system
- i got an interact system
how would i go about a "quest" system?
Copiedbuilding types is the list so why cant i add istantiated building to it
one that automatically updates?
share the entire script.
I need to see what you are actually doing.
define a quest system 🤷♂️
Depends entirely on what you mean by a "quest system".
Nothing in this script uses CopiedBuildingTypes
It's a private list with no uses in this script so it might as well not exist
i added it at the top
I can see that
its an empty list that i want to add stuff to
well i put a panel, and i have a TMP attached to it
basically i want to give the player certain things they need to get to the next quest, or even just have all the quests be finished (regardless of order), and give me a response
you have deleted the line that tries to call Add on CopiedBuildingTypes
thus removing the error, I guess
problem is, im not sure how to start
at first i was thinking a list but then it just sort of got more complicated than that
each quest would need their own script, i think
You will want to start with the quest's bookkeeping -- tracking objectives and deciding what should happen next
I think start by defining in detail what it is you actually want. What is a "Quest"? What does completing one mean? What kinds of quests are there?
Displaying the quest can come later
Find similar things that all types of quests have
then find "Groups" of quests - fetch quests, slay quests, etc.
you should really learn how to cache components. there is like no reason to do GetComponent<CityTab>() so many times in a row, store it
and make classes representing them
then if i want to add something to it what do i do
.Add
that's a GameObject[], not a List<GameObject>
i guess my question isnt exactly how to display it
ya i know im gonna try to fix that later
Oh right
In that case, @long jacinth , the answer is "You don't"
Switch it to a list and use Add method
What do you need to display
ok thank you now it works
displaying a quest sounds really easy. you just take some text from it and put it into a UI
to avoid confusion you should really be storing these as their type not Gameobject @long jacinth
i have nothing to display yet. im trying to figure out how would i go about creating a list of objectives, but each objective works different
like lets say i want the player to click 3 buttons (which would be its own quest)
collect some objects (quest)
and then i need them to click a switch (its own quest)
ok
and yes -- referencing everything as a GameObject makes it really hard to understand what is going on
like each thing would have its own logic, so i feel like each would have its own script
so I've been working on an objective system for my game
when instantiated it and added it to the list that means other gameObjects with the same script will have their own copy of the prefab right
do you use different scripts for each objective?
each gameobject in the list would be their own instance (with their own stats)
thats the bit thats getting me the most here
I only have a few kinds of objectives. For example, SingleObjective is either:
- Pending
- Succeeded
- Failed
If I want to tell the player to pull a lever, I give them a SingleObjective, then make the lever set that objective's state to "Succeeded" when the interaction ends.
I also have "combo objectives", which are just many objectives that all must succeed for the combo objective to succeed
So I'm keeping the actual game logic out of the objectives. The objectives are pretty much just checkboxes
i didnt think this bit would actually just stump me
i think im sort of getting something here but i should probably write it down before i lose it
Now, if you want things to happen as you reach various stages in a quest, you'll want to allow other parts of your game to listen to quest status changes
this is absolutely going to be a pain
The fun part here is figuring out the references
One option is to have each quest be stored in a ScriptableObject asset. This makes it easy to reference the quest itself, but you'll also need to be able to reference a specific stage in the quest
e.g. "This door is open if stage 2 is complete"
Maybe you could make each quest stage an asset, too
So a quest would be a list of stages (which you might go through non-linearly)

This would be nice for a lot of applications. A door could reference a quest stage and be open as long as a stage has been reached
colliders my beloved
i need a pencil
Note that I would avoid trying to store state -- that is, data that changes -- in these quest objects. These are just the definitions your game will look at
You might just have a class whose job is to remember the status of each quest and quest stage
That would make saving and loading reasonably easy
My approach usually is... write down the different things I'll need, figure out the different implementations (even code them if necessary), figure out what's common and can be nicified
ScriptableObject assets will unload if nobody is using them after a scene change. This results in fun surprises if you try to store mutable data in them
every quest is going to need its own bool isnt it
sure, but it'd be something like
Dictionary<Quest, bool> questsCompleted;
Serializing this so that you can save and load would require a little extra work
An easy approach would be to just do it by name, so you'd save out something like
{
"Eat 3 Apples Quest": true,
"Open Door Quest": false
}
the annoying part is that renaming a quest now breaks your saves
I use this https://bronsonzgeb.com/index.php/2021/09/11/the-scriptable-object-asset-registry-pattern/
It gives every asset a GUID (literally just the GUID that Unity creates to keep track of the asset, in my case) and then lets you find the asset by its GUID
so my save files look more like
I usually use the name as ID and have an idOverride param on these, so if I really wanna change the name, I can just type the old one as override
also, name is never used as DisplayName 😄
i can feel my will draining
Of course, you could also just hard-code everything if you want to
i cant do foreach() with a list right?
Especially if you don't have grand aspirations to create dozens and dozens of quests
of course you can!

foreach(GameObject i in CopiedBuildingTypes)
{
GameObject instantiatedButton = Instantiate(ButtonBuild, Spawn.transform.position, Quaternion.identity, Scroller.transform);
}
"object reference not set to an instance"
Perhaps Scroller is null, or Spawn is null, or CopiedBuildingTypes is null
Which line
"foreach(GameObject i in CopiedBuildingTypes)"
there is absolutely nothing wrong with making a game that's...a little jank in some areas
CopiedBuildingTypes is null
did i just instantiate stuff inside it
Watch the stream here:
https://piratesoftware.live
#Shorts #GameDev #Undertale
Undertale is an incredibly popular game and it's implemented about as cleanly as a 23 car pileup
I'm building a very elaborate objective system that neatly integrates with my AI system (so that AI characters can turn objectives into goals, then compute plans to attain those goals)
but the player won't care if the game is bad
(or doesn't exist)
Magic Glass
thor is a great motivator im ngl
i dont want to deal with the quest system but i know i cant avoid it forever
and i got this weird boost of motivation recently, and it was enough to get me to complete my inventory system in a way i liked, and just overall have an interacting system i liked
it will not last forever, and i should make use of it
You can always replace the system later if you need to.
A quest system would be great to have. But is it necessary?
he i am a beginner with xr interaction toolkit. When i try to pick a object up it doesnt work. I use xr interaction toolkit
Funky thing, when I use the spotlight it looks like this in the inspector, but in game it just spreads red light EVERYWHERE. Did I do something wrong when setting up the toggle on my button? Or did I mess up the code?
The button also only seems to work once or twice at most and then never again...
For reference, I'm using the built in render pipeline and using this with OpenXR
Put a log statement inside the function and see if it's occurring when expected. There's a possibility that the function is working but not as you're intending due to other stuff.
The... function? I'm mostly concerned with the spotlight not rendering properly
like, in the editor it looks clean like that but in-game it's absolutely not. it's a chaotic red mess everywhere
I was concerned about your statement in regards to the button not working consistently.
ehh, I think that's because I assigned it weird. I had assigned the button to the spotlight and not the controller
so it's just a problem with why is the spotlight a mess in game
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Movement : MonoBehaviour
{
public Camera playerCamera;
public float walkSpeed = 6f;
public float runSpeed = 12f;
public float jumpPower = 7f;
public float gravity = 10f;
public float lookSpeed = 2f;
public float lookXLimit = 45f;
public float defaultHeight = 2f;
public float crouchHeight = 1f;
public float crouchSpeed = 3f;
private Vector3 moveDirection = Vector3.zero;
private float rotationX = 0;
private CharacterController characterController;
private bool canMove = true;
void Start()
{
characterController = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
void Update()
{
Vector3 forward = transform.TransformDirection(Vector3.forward);
Vector3 right = transform.TransformDirection(Vector3.right);
bool isRunning = Input.GetKey(KeyCode.LeftShift);
float curSpeedX = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Vertical") : 0;
float curSpeedY = canMove ? (isRunning ? runSpeed : walkSpeed) * Input.GetAxis("Horizontal") : 0;
float movementDirectionY = moveDirection.y;
moveDirection = (forward * curSpeedX) + (right * curSpeedY);
if (Input.GetButton("Jump") && canMove && characterController.isGrounded)
{
moveDirection.y = jumpPower;
}
else
{
moveDirection.y = movementDirectionY;
}
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
if (Input.GetKey(KeyCode.C) && canMove)
{
characterController.height = crouchHeight;
walkSpeed = crouchSpeed;
runSpeed = crouchSpeed;
}
else
{
characterController.height = defaultHeight;
walkSpeed = 6f;
runSpeed = 12f;
}
characterController.Move(moveDirection * Time.deltaTime);
if (canMove)
{
rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
}
}
}
why does it walk on its own?
Scroller = GameObject.Find("ButtonContainer");
Spawn = GameObject.Find("Spawn");
CityTabObj.SetActive(false);
foreach(GameObject building in BuildingTypes)
{
GameObject InstantiatedBuilding = Instantiate(building);
CopiedBuildingTypes.Add(InstantiatedBuilding);
}
apparently copiedbuildingtypes is null
Where do you assign it a value
CopiedBuildingTypes.Add(InstantiatedBuilding);
That's where you add to the list
where do you actually create the list
at the top
List<GameObject> CopiedBuildingTypes;
hello everyone good evening peter here i just have a quick question i am using oncollisionenter() function but everytime is collide with my player to the object that has a rb and a collider the function doesnt start only when i move to the side and my cube crosses the collider with one corner is there any who can help me so that it calls the function when I collide with the collider?
That's where you declare the variable. Where do you actually create the list
do
List<GameObject> CopiedBuildingTypes = new();
wdym create the list
I mean create the list
after or before CopiedBuildingTypes.Add(InstantiatedBuilding);
oh so when making lists i have to do = new(); ?
You need to create the list before you can add anything to it.
If you want a list to exist, you have to make a list
oh
Yep
Short for
List<GameObject> list = new List<GameObject>();
how comes you can omit the end List<GameObject>(); ?
Because C# lets you do new() instead
i believe it was a C#9 feature: the type specification is not required if the type is known . . .
Yeah, I had a look and it's a c#9 feature for target-typed new expressions
per the example, the type is known on the left-hand side, therefore, it's not required on the right-hand side . . .
it is :D
how do i make a custom rendering pipeline. i am pretty experienced in shader programming but i have never really used unity. i want to make a renderer for a black hole it needs to be ray marching based since i also want a volumetric for the accretion disc. it would be nice if someone could tell me how to make this possible and pass the necessary information to the shader. (GLSL if possible since i have more experience with that)
thanks
Is it still doing this? I've seen that behavior when using a texture that doesn't have its wrap mode set to "Clamped"
rubs me the wrong way that you can define methods at a later point in your program than you call it
note that you would probably not make an entire render pipeline for this
Wrap mode is Clamp on the texture
I also noticed that the light can get into a sort of "bad state" when I changed the texture import settings. I had to remove and reassign the cookie to make it render properly again
That's one difference between a compiled language and an interpreted one
don't other c-based languages and ones like java (which are also compiled) require you to also define them before they're called? or at least by using forward declarations?
not as far as I know.
i could be chatting out my ass tbf
i'm more surprised that those languages don't allow it, tbh
i think it's really cool but it feels so bizarre
It implies that you can't parse the language without knowing if a symbol exists or not
Well
Parsing C++ is a complete clusterfuck
so that makes sense
i.e. that you can't parse this statement:
Foo(Bar);
without already having seen a definition for Foo
Spawn = GameObject.Find("Spawn");
CityTabObj.SetActive(false);
List<GameObject> CopiedBuildingTypes = new();
foreach(GameObject building in BuildingTypes)
{
GameObject InstantiatedBuilding = Instantiate(building);
CopiedBuildingTypes.Add(InstantiatedBuilding);
}```
``` foreach(GameObject buildx in CopiedBuildingTypes)
{
GameObject instantiatedButton = Instantiate(ButtonBuild, Spawn.transform.position, Quaternion.identity, Scroller.transform);
}```
idk why
but apparently the list is still not
Are both of these snippets in the same function
no the first is in a function i made and the other is in start
So, where do you create the CopiedBuildingTypes list you use in the second snippet?
it's easier if you post a link to show all your !code. snippets don't help give us an idea of what our code does or where . . .
📃 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 mean the oppisite
second one in a function i made and first in start
In that case, where do you create the CopiedBuildingTypes list you use in the second snippet?
List<GameObject> CopiedBuildingTypes = new();
Where?
That's creating a variable in start. Where do you create the list you use in the other function?
i thought i already created it in the start function
"CopiedBuildingTypes"
You've made a local variable in the start function.
That means when the start function ends, the variable ceases to exist
instead of creating a new variable, you should use the one you already have
then in this case what should i do since i dont want any data inside the list to be lost if i create it again
You need to assign a value to the field variable you declared in the class
so i do List<GameObject> CopiedBuildingTypes = new(); again?
You would do that where you actually want to create the list
but wont that remove things already in it if i do it agian
= means "Assign to". The variable CopiedBuildingTypes is a variable that can hold a list in it. Whenever you use =, you are changing the list that the variable holds.
There couldn't be anything in it already in that case since you're declaring a brand new variable.
so it wont remove the GameObjects stored inside?
Take a moment and think through what I just said
If you change which list the variable holds
It's a variable that references a list
wel where is the list
Nowhere, until you create one
That's what the error is
You can start by creating it at all
You aren't actually storing a list in your class variable anywhere
then how do i store it
With =
well i did that in the start function
No you didn't
then it gets lost because its the start function
You created a brand new variable, with the same name
You created a new variable in Start. You do nothing with the one you defined outside of Start
Tell me, if you made a variable private int x = 3
Tell me, how would you change x to 7 in start?
x = 7
Correct. Notice how you did not say "int x = 7"
Because that would be creating another variable
Now, look at what you put in Start for creating the list
Are you changing the value of CopiedBuildingTypes? Or are you making another variable with the same name
List<GameObject> CopiedBuildingTypes = new();
Oh I understood
This is creating a variable named CopiedBuildingTypes, and putting an empty list in it
I should have did CopiedBuildingTypes = new();
lordy lord
Right

Ok
i have an enemy follow player script which tells the enemy to follow player and i also have an enemy spawn script and im spawning in enemy prefabs, how do i set the player trasform(in the scene) to the script in my enemy prefab (in assets)
What was wrong with the answers I already gave you to this
i dont know how to implement it
Which one? I showed you a code example for one
and then you asked for other ways
and I listed them
Is there one you wanted to know more about?
Ask clarifying questions if you don't understand
You're not going to get anywhere just reposting the same question.
alr sorry
i dont know what any of the other ones mean and im not sure how to implement the other one
so ask questions
And I'm not sure how you can say you don't know how to implement it when i literally gave you a code example
If you didn't understand the example ask questions about the parts you don't understand
may i send u the code ? and u tell me how pls
Send me the code of what
spawn
Was there something you didn't understand about the code example I shared?
in the wave script i use is kinda complex and im not sure where to add it
It really doesn't matter how complex the script is. You add it at the point where you call Instantiate, and the reference to the player goes where all the other serialized/public fields go.
!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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm trying to get the particle to act as a trail for my meteor. I want it to always move in the opposite direction to what the meteor moves in. My meteor also rotates and I want the particle system not to rotate. I'll share a video in a sec
why does this not work? i forgot
as in why can't i assign the scripts in the inspector
What is a Rule?
a class
show me how you have defined that class
Okay, so it derives from MonoBehaviour
That makes it a kind of unity object, so that should serialize just fine
make sure that your code is actually saved and that you don't have any compile errors
do you have any objects with that component attached in the scene?
What are you trying to drag in?
no, is that required?
well, yes
ah
did you mean to refer to a prefab, perhaps?
the second screenshot shows a list of Rule objects in your scene
You should still be able to pull in a prefab
It just won't show up in the "Assets" list, even if you have a prefab with a Rule attached to its root object
for Reasons (tm)
okay so id have to make a prefab for each of them got it
Each what?
each rule (inheritance)
If you don't have objects in the scene, and you don't have prefabs, what were you trying to add?
i'm very confused by what you're doing now
the script 😭
the script is a blob of text
A script is not a Rule.
It's a TextAsset containing a class
It doesn't exist until it's on an object
Are you trying to refer to entire classes here, perhaps?
yeah now that you mention it that makes sense
yes
Explain what you're trying to actually do here
not your attempted solution: your original problem
i wanted to store the rules in an array, so they can be used to later validate an input from the player
each rule is its separate class as thats the best ive been able to come up with so far
Hi, I don't know if you can help me with this code. This code is supposed to make the YXZ axes appear when an object appears but it doesn't move it with the axes.
but they all inherit from Rule parent class
Okay, so what you really want to do is create some classes like this
public class GizmoHandler : MonoBehaviour
{
public enum Axis { X, Y, Z }
public Axis axis;
private Plane dragPlane;
private Vector3 dragStartWorldPos;
private bool isDragging;
public void StartDragging(Vector3 hitPoint, Transform parentPiece)
{
// Crear el plano de arrastre basado en el eje seleccionado
switch (axis)
{
case Axis.X:
dragPlane = new Plane(Vector3.up, parentPiece.position);
break;
case Axis.Y:
dragPlane = new Plane(Vector3.right, parentPiece.position);
break;
case Axis.Z:
dragPlane = new Plane(Vector3.forward, parentPiece.position);
break;
}
dragStartWorldPos = hitPoint;
isDragging = true;
}
public void HandleDrag(Vector3 hitPoint, GameObject parentPiece)
{
if (!isDragging) return;
Ray ray = Camera.main.ScreenPointToRay(Input.GetTouch(0).position);
if (dragPlane.Raycast(ray, out float enter))
{
Vector3 dragCurrentWorldPos = ray.GetPoint(enter);
Vector3 dragDelta = dragCurrentWorldPos - dragStartWorldPos;
// Mover la pieza y el gizmo
switch (axis)
{
case Axis.X:
parentPiece.transform.position += new Vector3(dragDelta.x, 0, 0);
break;
case Axis.Y:
parentPiece.transform.position += new Vector3(0, dragDelta.y, 0);
break;
case Axis.Z:
parentPiece.transform.position += new Vector3(0, 0, dragDelta.z);
break;
}
dragStartWorldPos = dragCurrentWorldPos; // Actualizar el punto inicial para el siguiente frame
}
}
public void StopDragging()
{
isDragging = false;
}
}
If you can help me with this
public abstract class Rule {
public abstract bool Validate(string input);
}
public abstract class AllCapsRule : Rule {
public override bool Validate(string input) {
return input.IS_ALL_CAPS(); // i made that up
}
}
public abstract class LengthLimitRule : Rule {
public int limit = 10;
public override bool Validate(string input) {
return string.Length <= limit;
}
}
These are not Unity objects. We're not going to attach these to game objects and put them in scenes
The immediate problem is that these things aren't serializable
That's an easy fix. Add [System.Serializable] to each class
This might be a dumb question but doesn't this break Single-responsibility principle? The project I'm making this for highly relies on SOLID principles for marks.
We can now put a public LengthLimitRule foo; in a component and serialize an instance of LengthLimitRule
this class has a single responsibility
it validates a string
i don't know how it could get any more single-responsibility than that
Question: Why are the rules components? What objects are they going to be attached to?
They're not, that's a mistake I was making
I don't know what this means
or i guess they are currently
so for example this question doesn't make sense so it would be validated with the rules and would return as invalid (false)
so you have a sequence of sentence fragments and you have a few rules for how they're allowed to be arranged
its meant to just be good enough to ask some basic questions about a word that the player is meant to guess
yes
im not sure if that impacts the structure you proposed
okay so Rule validates a List<SentencePiece>
instead of a string
The commonality between every Rule is that they look at an attempted input and say "good" or "bad", correct?
something like that, the nodes are GameObjects and they're checked per rule whether they contain an IPrefix, IDescriptor or IValue
If so, then this is the structure you're looking for.
yes
The larger problem with this is that, whilst you can do this:
[SerializeField] List<Rule> rules;
...Unity will only store the properties that are part of Rule. It won't remember any other properties.
it also won't let you pick which kind of Rule you want
There are several packages that solve this.
would i still be able to just brute force it with every rule and check if any returned false? since that was the plan originally
Yes, that's trivial
This is not using that exact package, but it's the same idea
I have a list of "scorers"
I can pick the exact scorer I want and configure it
in this example, the dropdown would let you pick AllCapsRule or LengthLimitRule
and then you'd get to configure LengthLimitRule, if you picked that one
That solves the hard part. Now you just do something like
foreach (var rule in rules) {
if (!rule.Validate(input)) {
return false;
}
}
return true;
ah okay that makes sense
if you use this package, your rule list will look like...
[SerializeField, SerializeReference, ReferenceDropdown] List<Rule> rules;
SerializeFieldso that it actually serializes this thing at allSerializeReferenceto tell Unity to correctly store child classesReferenceDropdownto get the dropdown UI (that's the only part the package is providing)
would I still use that package if I'm hardcoding the rules? in my case I want the rules to just check things like if prefix is in position[0] etc
The rules could be very simple
The point of the package is to let you pick which kind of Rule you want
Otherwise, you'd need a List<RuleOne>, a List<RuleTwo>, and so on and so forth
ah okay i see what you mean
List<Rule> is what you want -- you don't care what the exact rules are
without SerializeReference, this gets saved wrongly, and with SerializeReference, you don't get an inspector UI for it!
hence the package
Now, if your rules are all just "X in position 0, Y in position 1, Z in position 2..."
I think I have a misconception about how I can update the parameter of a blend tree via script. I used:
private static readonly int X = Animator.StringToHash("x");
private static readonly int Y = Animator.StringToHash("y");
// ...
_animator.SetInteger(X, (int)direction.x);
_animator.SetInteger(Y, (int)direction.y);
But apparently this does not reach the blend tree? It only updates the animator's parameter, which I thought would then update the blend tree with the same name
ill take a look at it first thing tomorrow morning then since i feel like if i implemented a package rn id set everything on file lol