#💻┃code-beginner
1 messages · Page 64 of 1
i used audioclips this time
it worked, however it caused a different issue
when i was shooting (playing the audio) the audio didnt move along with my character
so if i were to run sideways the audio would lag behind
Are you adding the clip to a source and playing the SOURCE?
Is the source ON the player?
i suppose so?
not exactly sure how you mean
Could somebody please help me with this jittering issue
// Update is called once per frame
void LateUpdate()
{
if (Follow_Position)
{
// Get target values
Vector2 TargetPos = Ship.transform.position;
// Get default value
Vector3 CurrentPosition = CameraObject.transform.position;
// Calculate target values with static offset for depth
Vector3 FinalPosition = new Vector3(TargetPos.x, TargetPos.y, -10);
Vector3 CamAccel = new Vector3(Rigid.velocity.x * Velocity_Mult, Rigid.velocity.y * Velocity_Mult, 0);
if (CamAccel.magnitude >= Velocity_Dist_Cap)
{
CamAccel = CamAccel.normalized * Velocity_Dist_Cap;
}
FinalPosition += CamAccel;
// Lerp final position
CameraObject.transform.position = Vector3.Lerp(CurrentPosition, FinalPosition, Hardness_Position * Time.deltaTime);
}
}
It happens when I edit the speed and have the ship move really fast
Show your code for playing it
You should use a paste site for this much code
Well you're using PlayClipAtPoint.
Which plays the clip at a specific point
So....
It won't follow of course
Try PlayOneShot
oh
!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.
alright ill try
Your lerp is messed up
Don't multiply t by deltaTime
do i just replace the PlayClipAtPoint with PlayOneShot?
Yeah, check the docs because the signature is different
signature?
How do I set the position of an object to be edge-to-edge with another object?
There's some vertex snapping options in scene menu near the top left, but it's not the greatest
I want the player to change the Position if clicking the Button
what's a signature?
The parameters of the method
oh alright
Make it through the center of the object, plus 0.5 of its diameter. If you want through the code.
thank you very much, got it all working now
How to make the Physics.OverlapBox exactly around the object, given that the object is not static, it can rotate around its axis. Do I have to use all 8 angles of the object to create this? Because I took Vector3 ((bounds.min.x, bounds.min.y, bounds.min.z) and Vector3 ((bounds.max.x, bounds.max.y, bounds.max.z)), but when the object rotates around its axis, it doesn't exactly do what I want.
In simple terms, the goal I want to achieve is to verify that the object on which the script hangs has an intersection with another object other than the ground and its daughter objects.
The OnCollisionEnter method doesn't work for me, so the method described above has to be called once at the time I need it.
There's a little sketch of my code.
https://hatebin.com/bwyoybswvv
Don't worry about all the unnecessary variables and the general crappiness of the code, I'm just experimenting.
Thanks in advance for any help.
It still jitters, unless I have t as exactly >= 1
I managed to do it with this:
transform.position = new Vector2(xPosition, otherBackground.transform.position.y - otherBackground.GetComponent<SpriteRenderer>().bounds.size.y);
```Both are the same size, so this works for now.
meant to me?
No to myself
Seems to work pretty well
https://gdl.space/poyereteno.cs
https://gdl.space/fiyogiwufu.cs
https://gdl.space/bovufiqeqi.cs
Theres the code if someone wants to mess with it
Having t be 1 means it is the same as directly the position to b.
Consider just using MoveTowards
Right now, your lerp is "jiggling" up and down because of the deltaTime
Another gameObject. Two backgrounds that scroll down, when one gets out of the screen, the other is on screen and the OG gets tp'd to the other's edge.
but i dont need that
Yea which is why I said that I responded to myself
So that if someone stumbles on my message with a similar problem, they have a bit of code and a brief explaination, so that they can try it for themselves, in the hope that it could solve their problem
I removed the delta time and it was still jittery
also, I changed it to use MoveTowards, I still get weird effects
Yeah, just doing that isn't gonna fix it at all
I'm not sure. Lerp was just the first thing that jumped out. I feel like it's an issue with the transform and rigidbody fighting eachother
Have you considered just using cinemachine?
You didn't post your full code, so... I don't think people can help you yet.
I would primarily like to know why this problem is happening and how I can fix it
It doesnt happen during normal gameplay, I just make the speed really fast to stress test my scripts
Rigidbody/transform fighting afaik
What do you mean by them fighting eachother?
Rigidbody moves with physics, transform doesn't
You want to do rotations and movement with the rigidbody if younhave jt
So this is a unity limitation which I can do nothing about?
I move the ship using rigid body
with fixed update
transform.position =
Is not rigidbody movement
If the ship is the issue, show THAT code
i cant install package 
As I said before, use a paste site
Not a code question
#💻┃unity-talk
And the server is down
private void FixedUpdate()
{
// Limit the velocity to MaxSpeed
if (Ship_Rigid.velocity.magnitude >= MaxSpeed)
{
Ship_Rigid.velocity = Ship_Rigid.velocity.normalized * MaxSpeed;
}
if (Mathf.Abs(Ship_Rigid.angularVelocity) >= MaxTurnSpeed)
{
Ship_Rigid.angularVelocity = MathF.Sign(Ship_Rigid.angularVelocity) * MaxTurnSpeed;
}
// Calculate and apply engine force
float EngineForce = MovementInputRaw.y;
if (EngineForce < 0) { EngineForce = 0; }; // Remove backwards force
EngineForce *= Acceleration;
EngineForce *= Time.fixedDeltaTime;
Ship_Rigid.AddForce(Ship_Rigid.transform.up * EngineForce, ForceMode2D.Impulse);
// Calculate and apply rotation torque
float RotationForce = -MovementInputRaw.x;
RotationForce *= TurnAcceleration;
RotationForce *= Time.fixedDeltaTime;
Ship_Rigid.AddTorque(RotationForce);
// Calculation rotation angle
Vector2 ShipToMouseDir = Ship_Rigid.position - Mouse_WorldPoint;
float ResultAngle = Mathf.Atan2(ShipToMouseDir.y, ShipToMouseDir.x) * Mathf.Rad2Deg + 90;
// Apply final rotation
//Ship_Rigid.rotation = Mathf.LerpAngle(Ship_Rigid.rotation, ResultAngle, TurnSpeed * Time.fixedDeltaTime);
//PlayerShip.transform.rotation = Quaternion.Euler(0, 0, PlayerShip.transform.eulerAngles.z);
}
"Use a paste site"
!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.
Probably want to limit velocity AFTER adding force. Otherwise it happens in the next FixedUpdate
unfortunately that didnt fix the problem
Hello! I am currently trying to develop a shooter game but before I do that, I am following Code Monkey's Turn based shooter game. Non of the actual coding terms have really stuck in and I would like to know how to get better at coding
Think my pool is legit now
His code is usually kinda nasty but consider just doing the official unity tutorials to get a general idea of it all
ok
void Update()
{
earnText.text = logic.coinEarnings.ToString() + " /sec"; //line 19
}
``` someone know why this works at pulling the information from my other logic script, and it also works updating when i press play, however i get the error spammed :
"NullReferenceException: Object reference not set to an instance of an object.
updatePrice.Update () (at Assets/updatePrice.cs:19)"
and for a follow up. For actually getting my roots in and starting a shooter, what unity tutorial would be best?
earnText, logic, or coinEarnings (or some combination) are null.
Probably the text if you say you can get the values from logic
Ok thanks!
There's a mix of tutorials, and I believe it goes over raycasting and such, but it's not specifically shooter tutorials
public LogicScript logic;
public Text earnText:
public int coinEarnings = 0;
``` i already have them like this, though so i am confused
you can always apply the logic to your games though since it's not exclusive to those specific tutorials
Hard to tell what the issue is. Pretty sure it's the camera struggling to keep up though. At high values the ship just shoots far enough forward for the single frame difference to be noticeable.
That is a declaration, where do you assign the references?
What you have there is null until you get an instance
That is probably whats happening yeah
Yeah I just need to understand basic things raycasts, best way to move characters, clean code, optimization etc etc
i seen a dude raycast each toe on a frog so it dynamically reacted to the plane
was so cool
Yeh pre sure he was making it to sell
some crazy shit though imagine doing that with an octopus or something
it keeps returning the error even after its null though
The error is BECAUSE it's null. What do you mean?
Checking the code now
Sorry, i meant after it stops being null haha
Yeah, where do you get scoreText?
Where does it stop being null?
public void upgradeCoins()
{
coinEarnings = coinEarnings + 1;
}
?? Where do you get the scoreText object?
Maybe ive done it wrong but i just have it like this
it does what i want it to do but it just gives me errors
Wait, what line gives you an error?
i'd bet there's probably another component of that type in the scene where something has not been assigned
it says ```c#
void Update()
{
earnText.text = logic.coinEarnings.ToString() + " /sec"; //line 19
}
Type t:updatePrice into the hierarchy search
like this
So you have two
Look at Text
On of the objects is causing the error, the other is working
ah yeah youre right
the script was attatched to both
working on one, not on the other
thanks alot 🙏
I know that this is the right channel but i dont know Where else to put it
Little help pls if i touch a key on my keyboard it goes to something. For example if i touch e it opens files. I think my Windows-key is on or something pls help turn this off
Doesn't sound unity related at all.
Maybe try restarting your computer
and/or trying a different keyboard
Ye i know
hey this kind of got lost, and I could use some help
my prefab doesn't update!
prefabs cannot reference in-scene objects
Prefabs cannot reference objects in scenes
when I drag the prefab into the scene, it doesn't reference anything from the scene
even though that's how I had it before I turned the game object into a prefab
yes because the prefab does not have references assigned. because applying the overrides does not magically make the prefab able to reference the in-scene objects
you'll need to pass the references to those objects when you spawn the prefab at runtime
https://unity.huh.how/references/prefabs-referencing-components
Prefabs cannot reference objects in scenes
ah oh ok thank you!!!
thank you all!!!
hi! i'm making a dungeon generation system and i want to spawn a boss room at the bottom row. however, the random room i want to turn into a boss room isnt destroying itself making my boss room not being able to spawn
Weirdly done
But if the room isn't being destroyed and the boss room doesn't spawn then it just seems like your condition in the if statement is false
Debug the values of roomDetection and levelgen.stopgen
So your overlaping circle doesn't detect anything
i think its because its attatched to my level generator and my level generator stops moving after the level is generated so my overlap circle doesnt rlly detect anything
Either way, I'd just slap this logic into the Level Generation itself
okay, ill try that
And generate the boss room alongside other rooms within the generation itself
No need to play around with physics overlapping and stuff like that
okay i've put the boss room spawing logic in my level gen script and now it broke the generation a bit (my extra rooms away from the main path aren'ts spawning) and im also getting an "index out of bounds of the array" error
Can't say much without looking at the code
But the second error is fairly straightforward, you're trying to access an element out of bounds of an array
!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.
https://paste.myst.rs/46dy8jbw (at line 133)
a powerful website for storing and sharing text and code snippets. completely free and open source.
im so sorry lol 😭
Well, since you're getting an index out of bounds of the array error then it seems like the spawns array contains less elements than you're trying to access
Show what exactly public Transform[] spawns; is in the inspector
omg im actually dumb
i mixed up the names and the array
im so sorry for wasting ur time
No worries
now it's doing everything perfectly except its spawning the boss room on top of an existing room but tbh i think ill just leave it like this for now
tysm once again!
It would be probably good to save these rooms into some sort of 2D array and just swap out one of the bottom rooms (rooms[max or 0][random] - depends on your indexing) for the boss room
Didn't read the whole code but using physics circle overlap seems a bit weird for level generation
thats actually a lot more efficient thank you!
Over 20,000 objects i would say this isnt bad but i can do better maybe
Consider ECS?
Those are just static primitive shapes, and you still get down to 4fps just in the time I watched
Or look into gpu instancing
You could definitely have that much at a decent fps
!code
I put them all to static just now but theres something in my code causing extreme lag, but ill definitly check those out
📃 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.
Hey I am using SQLlite with unity for my offline database. I just made an export to test for mobile but the already tested and functional code is refusing to work there
theres not much you could actually do, doing anything 20k times frequently is going to lag. If you truly need a large amount of objects then yea you should look at ecs. I assume what you were doing was just a stress test on objects that did nothing, once you actually start to implement gameplay this isnt gonna be running at all
I think it is related to my files. I dragged this file from my unity editor folder into my project that made it work (As I was told to) on my PC. but the file name had windows attacthed to it
I feel like I have to somehow get a mobile version
Not really i built a seperate project to build a culling system that i could implement into my game, now will there be a lot of objects no, nothing like that but if i can get it to do well with a lot of objects then i dont have to work, then i can start working on making it work for moving objects
I think thats an improvement
why is it that sometimes my rooms dont connect with my boss room (red room)?
https://paste.myst.rs/mcflt6sc
a powerful website for storing and sharing text and code snippets. completely free and open source.
I was following brackeys rpg tutorial and in stats episode I had a problem about modifiers not adding.
PlayerStat :https://hatebin.com/brveegyegz
CharacterStats :https://hatebin.com/oemqfhfurh
Stat :https://hatebin.com/vzwnqrwubm
EquipmentManager:https://hatebin.com/cucdffbbcb
Debug.Log("Equipment Changed"); this line works but rest doesnt.(it's in playerstat)
Are you doing anything that would guarantee they are connected? Or just picking random rooms?
picking random rooms
Well there's your answer
im only guaranteeing that all the other rooms are connected to each other
You need to use graph algorithms like DFS to ensure your exit is connected to the entrance
how would i go on about doing that in your opinion?
cuz right now im usinga direction algorithim to see where i should place the next room
What's the best way to do FPS movement that feels good?
https://paste.ofcode.org/ARJ7TaxN8xYgxWR3NDPjtE
The overall sql libraries work on my Pc when testing but immediately I export to mobile, it doesn't even export at all if I don't have both line 3 and line 8 commented out
Like Tarkov and COD
I tried getting 'sqlite-android-3440000' from https://www.sqlite.org/download.html and adding it to my project but it still didn't work
Perhaps you should use sqlite directly instead of relying on third-party libraries
one part of anti - cheat is preventing people from straight up adding new code to your game right?
Mmm... Not really. You can't really add code to a compiled app.
oh. so I just need to make it so that no modifications to memory can have a real impact?
The most effective anticheat generally involves making sure that a modified client can't do any damage to the experience of other players. This generally means:
- detection + banning
- server side validation of possible behavior
there's generally little you can do to prevent a determined attacker from making modifications to your program on their own hardware
so it is possible for them to inject their own code or no?
I understand that they can prevent calls and change values through memory
of course it's possible
they can do literally whatever they want if they know what they're doing - it's their hardware at all
assume they control all the bits in memory.
Then you'd be a bad person?
You'd get zero downloads
isn't that how valorant's anti cheat works
and your app would be blacklisted by antivirus programs and windows defender
And all that wasted effort combating your fear would be for nothing.
partially, yes, they require very invasive low level access. But no such scheme is perfect
Yes but people play Riots games. People are not going to play some hobby developer's game if it requires installing additional software.
ofc, i was only joking
you can try stuff like https://easy.ac/en-us/ but nothing is perfect, it needs to be combined with other measures
I wouldn't worry about it for now. You should be grateful if someone considers your game fun enough and worthwhile enough to develop cheats for
worry about it then
focus on making your game fun
yeah I get it, but at the same time i'm also trying to learn and this is good practice ya know. It's higher level coding than most of the stuff i've done
i just have one question
so like, if I achieve this in such a way where they would have to add full on functions in addition to their overwrites to bypass my server authority, would that at least be difficult to do?
I guess this it would be enough to the point where if I had any players, it would take some time to develop a cheat, and at that point, I could add further measures to prevent it
Anti-cheat seems to be a game of cat and mouse really
which part are you asking would be difficult? for the user or for you?
There are some parts that are easy to protect against by just having everything done on the server. If we take valorant for example since it was listed above, you wouldnt be able to add any code at all which lets you shoot or move faster than you should. Technically they could try to do it client side, but server side nothing will happen. There are other things though like wall hacks, which still exist to this day, which you cannot fully prevent. You have to tell the user where everyone is at some point, so people can modify their own client to show that in a benefiting way.
For the user. What you said makes sense. I've never tried to hack or cheat in a game before, so I don't know much about the process. Obviously, there is a difference between developing a cheat and installing it; i guess i'm asking about both parts. How hard is it to develop, and is there any difference in difficulty of installing it for the average user?
"Difficult" is kind of a relative term. Users range from "Facebook Uncle" to "Script Kiddie" to "People Who Know What They're Doing".
That last category will likely get past almost anything you come up with
Assuming they care enough
Lets say "script kiddie"
I think would be more objective if we measure solely on complexity.
And the first two might buy scripts/programs from the third
indeed
yeah that's why I asked if its equally easy to install a cheat no matter how complex that cheat is
Yes, no matter how complex the cheat is, it can be packaged into a program that can be sold and installed easily
This is what most "hackers" in online games are using
they buy a cheat from somewhere and install it
you're right that it is a game of cat and mouse. To properly understand how to make an anti-cheat, you need understanding of how to cheat in the first place. Although premade anti-cheat already exists so no real reason to make your own.
Developing something to cheat can be extremely easy, depends on how much you prevent against. Installing it can also be really easy, if the developer of said cheat makes it user friendly. In my experiences, people who make the real cheats do not want to share it publicly because they make these for personal benefit.
If we take the most basic example, what some call a packet client, it sends custom packets and practically has no way to be detected. The only detection would be if the server notices something is off and bans the person
For the people who buy it, not make it: Sometimes its as easy as pressing "install", sometimes its as hard as needing to install an IDE then compile the scripts.
How can premade cheats exist if the program they are trying to get into uses different architectures?
I understand that you can have a premade cheat that gives access to variables and stuff, but that doesn't mean it works right?
it's premade for the specific game it's meant to attack
Ah yeah there are premade anticheats which attempt to do things like memory validation on your program to make sure nobody has modified the program
among many other techniques
But the problem with things like this is that the anticheat itself can be attacked/modified/neutered
and like you said - cat and mouse
Okay so that answers the second part of my question, in terms of how long it would take for someone to develop a cheat, is there any way to estimate that?
Comes down to the skill level of the person
and the tools they're using
not really estimable. I bet nowadays AI can be used 😆
Well in my brain, wouldn't it require some level of analysis / understanding of how the program is running?
yes, but there are well known patterns. For example the Unity Engine itself doesn't change much between unity games, and if you're using a well known networking library for example. that doesn't change between games either
Is it that easy to exploit a networking library made by unity?
or are you just saying that same networking library means similar architectures
Sure why not - especially since many of these things are open source and easy to analyze
not at all possible to estimate, ive seen real cases where people found a work around to a new anticheat patch the same day the patch came out. This also really depends on what the cheat is for, some things are not possible to cheat
Alright well I really appreciate your guy's time and patience, this isn't exactly the easiest topic for me. I think for now I'll just stick to the basics of server authority and stuff, later i'll worry about maybe finding an external anti-cheat, and tackle any futhrer problems if / when arise. That's really all I can do anyways.
Yeah don't worry about it right now
It's a good problem to have in that it means your game is popular enough to warrant attacking
if you don't believe in your game, then why make it? 🙂
Unless your game gets extremely popular, the people who know what they're doing probably wont even bother making a program to cheat. Mostly i see these done if it involves real life money
Its more fun to find in game bugs anyways
yep - no audience == no buyers for cheats == no cheats
If theres a market for in game item to real life money then that'll provide incentive. Like csgo markets or underground trading of currency
Why is it that in this script, the jump event causes the object to rise higher than it should? (Detail, the "speed" variable has a value of 5.00f).
Unrelated (?) but you should not be moving a rigidbody with transform.position
Why are you moving with transform.position if you are using a Rigidbody?
Oh and you are adding rb.velocity.y to the position too
Definitely not unrelated - in fact as written this code will always produce:
- jitteriness
- inconsistent results due to the physics-ish movement in Update
Because with RigidBody the movement is different from what I'm looking for. For example, with "rigidbody.velocity" it doesn't look the way I want it to.
basically - delete that crazy line of code
You need to decide if you want to use a Rigidbody or not
if not, remove the Rigidbody or make it kinematic and stop setting the velocity
if so - stop moving via the Transform
pick one
Then I'll use Rigid Body.
then delete the transform.position += line
Did your dislike have to do with falling
People have issues getting gravity to work with velocity sometimes.
I need the rigid body, to jump
You can do jumping without a Rigidbody
Nah, you CAN do it with transform
Just needs some math that the rigidbody physics would otherwise do for you
Write a little code
I even tried, but I couldn't, maybe because of the effect of gravity
it's not that complicated. You just need to track the object's current velocity and apply gravity
gravity is very simple
it's basically just cs velocity += gravity * Time.deltaTime; in FixedUpdate
Wow, that's stupid of me. I appreciate it.
that being said I really think you'll have an easier time with a Rigidbody
especially as a beginner
Rigidbody.velocity?
don't conflate different issues
gravity is gravity
you can deal with other things with other code
Oh yes, now I get it
If you use transform, then velocity would be a Vector2/Vector3 that you make yourself
English only please, also don't ping me out of the blue.
Gravity makes things go down generally
Kinda the opposite of a jump
But I guess falling is part of jumping
i hope he dont gravity*-1 to make his character jump
i think the main question is how to make the char jump
so the answer is like AddForce or something
You can set y velocity to some positive value or use AddForce.
if i call a coroutine in Start(), will the script not run Update() until Start() has finished?
The script will run as normal
the coroutine will not affect the other normal operation of the script
i need to use "layers"
not coroutine my bad
That is how it always would happen. Coroutine or not
yeah im dumb
Can I pause the execution of a script until a certain event?
You have to be really specific about what you mean by "pause execution"
You can disable it.
Or set an early return in update that you can toggle on and off (which allows partial updates and only stopping after some point)
If you want Update not to run - you can disable the script.
Like I need this script to behave so that when it is initialized it recieves a value from the server as one of it's instance variables, which takes time
Essentialy this is for creating a tick system. When a player spawns in, I need it to jump to the currentTick, which it has to retrieve from the server, and I don't want it do anything until it has recieved that variable
So, if Start() hasn't finished running, will Update() still run?
Nothing in the entirety of the engine will run until Start finishes running
Unity is single threaded
if you yield return null in IEnu Start(), the next lines will go on next frames, Update will continue as usual
If you're doing network requests you'll want coroutines or some kind of async
alright, i'll just add a little bit of code to Update , it wont be pretty but it should work
thanks
cant you just have another object handling it?
then enable the thing when your task is done/ready?
no unnecesssary consistent check in Update
not quite sure what you mean?
have another thing wait for the request, when the request is ready, enable the thing with the update that you wanted to delay
yeah that's what I'm going to do now 😄
so you dont need```cs
void Update()
{
if(ready) dothings;
}
This is what I was going to do
Is 2d Vector still in the new input manager?
2D vector composite was renamed a long time ago to up/left/right/down composite
See their edit
Action Type -> Value
Control Type -> Vector2
as always
The particular tutorial you're following should show this I believe
(p.s. I hate that tutorial)
Which tutorial is it?
The one with the action map name "onFoot" and that names its input action asset "PlayerInput"
Did you do this?
it will show up when you do that
how can I reference MeshPro UIS in external scripts?
what is "MeshPro UIS"?
when i use GameObject.Find gives error
I assume you mean TextMeshPro components?
TMPro
they are TMP_Text
yes
basically, I need to access a TextMeshProGUI in a script that isn't associated with that object.
There's nothing special about it
you reference it like any other Unity component
the class name is TMP_Text or TextMeshProUGUI
I understand, but the problem is when it comes to finding the object on the map, do I use GameObject.Find or TextMeshPro.Find?
Neither
make a serialized field and drag and drop in the inspector
There is no such thing as TextMeshPro.Find
GameObject.Find only finds GameObjects, not components directly. As always
is there any other way besides graphs? i feel like theyre a bit too complicated for my level
a maze is inherently a graph
If you don't want to deal with graphs, don't make a game that deals primarily with something like a maze that is best represented as a Graph
Any other way is going to just be a more complicated less efficient bastardization of a graph
I have an audiosource that plays throughout the game (except when paused, at which point I use Pause() to pause it). when running in my editor it works perfectly fine. however after I build it to webGL and play it through itch, pausing repeatedly causes very weird behavior. it seems to skip ahead in the audio clip. Since it doesn't seem possible to reproduce within the editor, I'm not able to do much in the way of troubleshooting at the moment (I can make a dev build if need be, but that'll have to be later tonight).
Are there any quirks about webGL builds that might cause unexpected behavior with audio files when pausing the game?
Is there a simple movement script thats easily editable
Not sure if this is the right channel but if anyone would show me some docs for Cg, currently trying to learn it
new not very good, I just need something that I can edit
Find a tutorial for the specific type of movement you want
Assuming you mean c#, the pins of this channel have some, I also like
https://www.w3schools.com/cs/index.php
I mean like shaders.
Ah, I didn't get that from "Cg"
I think the #archived-shaders channel has resources in the pins
ty
I got it working. few questions.
1). how would I get rid of that annoying clipping?
2). how would I make the gun also follow the look up and down motions?
- Typically by making a separate "arms only" mesh rather than viewing your full body mesh from First person perspective
- the arms/gun should be children of the camera (and often rendered on a separate camera to prevent clipping into walls etc)
Your IDE is not configured
huh?
The thing you write code in is not set up properly
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
- in the future I might want to make this multiplayer so how would I have it render the arms for the player themselves but everyone else has the army model
1.25. It has the clipping on the gun to
1.5 I also kinda want to have the player be able to see their own body
No it is
- worry about that when you get to multiplayer. You're a long way off. Anyawy it's easy just disable the body renderer for you and enable one for the arms
Not from those screenshots it isn't
This is unquestionable.
The colors are all wrong.
Do you get code completion?
Do errors get underlined red?
It has unity developer tools option and it's the unity external tools thing
Irrelevant.
Does it do the things I asked?
The colors are off though. Monobehaviour and other types would not be white if it was configured right
to the last 2 yes
Ok surprising you get that when it isn't configured all the way.
Alright then, those are the big two, so you can probably get by as is
Someone may call it out in the future if you post screenshots
Just tell them you get code completion and error underlining
Hey, I have around 200 enemies in my scene that I'd like to batch render, i enabled GPU instancing on the material, do i need to look for anything else?
I had these lines running before
Renderer.material.color = Color.Lerp(Renderer.material.color, Color.white, 0.02f);
[...]
if (value < maxHealth)
Renderer.material.color = Color.red;
``` but even disabling that, the status still shows 0 batched objects
Are they skinned mesh renderers?
Where are you checking the batches info?
Material of the enemy
You should look at the frame debugger
You get rid of the clipping by having the arms seperate and you can render the gun and hands with a seperate camera to make it seem like its not going through walls and such, also if you want legs you can also make the legs and torso seperate so you can see the legs when you look down, you seperate the arms for adjusting them, and you can also mess with you camera clipping and for multiplayer you would use a sperate mesh for the other players view along with normally its own set of animations, also i would avoid having the head on the players mesh makes your life easier
doing that rn, any idea where i can find the batching in there?
Batches would appear as draw calls. They would literally say "batch xyz" afaik
https://img.sidia.net/ZEyI5/PurUQIBI53.mp4/raw it appears as if it draws it all in one batch, statistics in editor says 0 saved by batching though
Yeah. Statistics is unreliable. Shouldn't be looking at it.
wow what a mess 😄
It was always fishy, but especially since they released the SRPs.
They did mention making it more reliable a few years ago, but I guess that didn't work out.🤷♂️
What wdym of course it worked out 
Maybe it is fixed in the newer editor versions idk.
Maybe the fix is not included in the beta🤷♂️
is 2023 even LTS?
It often lacks fixes of the lts, since they're working on a separate branch
or should i say gonna be LTS
It's not lts yet, is it
Internet says "coming in April 2024"
mmmmm is that right
Lts's are always released one year later.
true
Oh, it's tech release that's in April. The LTS itself is in 2024 Q4.
Where's the problem, so I can't jump while moving the object horizontally?
You are first adding a force (which changes velocity), then you go ahead and override velocity
Yeah dont use force and velocity together, its either you do force based movement, or directly change the velocity
Why are you adding x velocity to your force?
Why are you multiplying your force by DeltaTime?
That also anything to do with physics you dont multiply with any type of time
One guy told me it was good practice
who did?
(also which question are you answering)
GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit
Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...
Whichever question you are answering, the guy was wrong
this guy
I think you miss understood, Time.deltaTime can used with many things, its very useful but never physics
Can you give a timestamp?
Anything physics should not and will not work when being multiplied with a time variable
nowhere in this video is deltaTime used with a force
deltaTime is good practice where appropriate, this is not such a place
in fact best practice is not to add forces in Update in the first place, though it's forgivable with an impulse one-off
wow
Addforce will work with it.
It'll just need a huge multiplier and will go up and down
So it would be bad to use it there haha
I'm going to remove that right away
if you want to know the proper practice of Time.deltaTime you can watch Acerola he does a really good explanation
Ok thats fair XD but like really no point
Time to learn the Mathmatical Concept of Frustum Culling
Unity does that by default btw
Yeah but its good to know
Sure =)
I lied it wasnt acerola its this guy https://www.youtube.com/watch?v=yGhfUcPjXuE
DeltaTime. This video is all about that mysterious variable that oh so many game developers seem to struggle with. How to use DeltaTime correclty? I got the answers and hope this video will help to deepen your understanding about how to make frame rate independent video games.
0:00 - Intro
0:34 - Creating The Illusion of Motion
1:11 - Simple Li...
I was gonna say, I hadn't seen that one and love acerola.
I DID watch that video. Pretty good! Got a worse score than I hoped lol
XD same
How would I make this script work if it's on my camera
thank you
Why is it on your camera
How do I make it so that you can collide and physically interact with an object, but make it really rigid, so that it can't be pushed by another object.
Give it a rigidbody and make it kinematic
to try to prevent clipping and have the hands follow the y axis
@amber dome Or just give it a collider and no rigidbody at all
Why would PlayerMovement be on the camera?
Anyway just reference the correct objects, that's all.
I would advise to not put it on the camera, the player movement and the camera movement should be seperate
@wintry quarry @teal viper just pretend i didn't ask those questions, my brain turned off a lil bit
if (belt != null)
{
beltInSequence.Add(belt);
return null;
}
does anyone know how I could be getting a NullReferenceException error at the beltInSequence.Add(belt); line when there is clearly an if statement that should prevent the line from running if belt is indeed null
I also checked this with a debug.log put right before the line logging the belt.gameobject, and it is indeed not a null value
How about the list
is the list initialized?
it should be
belt being null would never cause that exception there anyway. Adding null to a list is perfectly fine
it's clearly the list itself
this isn't enough context to know if the list is initialized tbh
what does a list being initialized mean?
Log the list before you call add
assigned to an actual object
do you assign it to null anywhere? is the script saved?
there's nothing preventing this variable from being reassigned to null for example
Debug.Log right before use or use of a debugger is required to prove it's not null
ahh that could be it
assigning a list to null isn't the same as clearing it?
no...
it's like throwing the bag in the trash
as opposed to clearing which would be emptying the bag
not at all. there is a method to do that . . .
x = null;
^ "how could x be null???"
well I didn't even know it was an issue with x to be honest
I'm using "x" as an example
how do you access variables in a class of an object from another object? Say Ball1 collides with Ball2, I want each object to get each others Traits
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallScript : MonoBehaviour
{
public class Traits
{
public float Speed;
public Color Color;
public Vector3 Scale;
// Constructor for Traits class
public Traits(float speed, Color color, Vector3 scale)
{
Speed = speed;
Color = color;
Scale = scale;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall"))
{
StopBall();
}
//StopBall();
if (collision.gameObject.CompareTag("Ball"))
{
Debug.Log(this.gameObject.name + " collides with " + collision.gameObject.name);
}
}
}
}
well right now you haven't actually given the BallScript a Traits field
so doing that would be step 1
step 2 is use GetComponent to get the BallScript component from the object you collided with
from there you can read any data you want
sorry I don't get this part. for step 2 I already tried it it says
you need () to call a function in C#
omg I'm dumb
im building a flappy bird game but the pipes are spawning closer together than i want and I cant figure out how to increase the gap between each spawn
Please provide reasonable context if you want to be helped. This is done with !code and assets we don't know about so you should share what you have done so that we can determine what might be a solution. #854851968446365696 -> 🤔 Asking Questions
📃 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.
assume your pipe have constant height h and spawn position y of bottom pipe is b
so the top of bottom pipe is h/2+b and you want the gap has gh height, so you just set the spawn y position of top pipe be h/2+b+gh+h/2=h+b+gh
yeah sorry here is the spawner code in its entirety :
https://hastebin.com/share/desoqototo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Short answer, increase heightOffset
Judging by the code this is the main variable that determines the final Lowest and Highest points of the pipe, no?
Oh I thought he meant horizontal close, not vertical close. 
Also, you don't need that timer variable
yep
oh alright
Now in terms of improving the code generally, I advice you made those variables private, use the correct naming convention (Private instance fields start with an underscore), and use the SerializeField attribute for them.
The point of this is to avoid exposing variables more than they have to be. Currently they are public and can be modified from anywhere, even other classes. Making them private restricts modification to just this sole class. This is better in terms of readability and also because you would never (ever!) write public fields.
The SerializeField attribute "serializes" your fields to be visible in the Unity inspector. This allows you to modify the fields from there when you are testing various values.
The result is being able to adjust the height offset whilst playing the game so you can get the sweet spot.
damn thanks thats helpful, i was following online resources so thats the reason for the public variables and other small inconsistencies
That's totally fine, just learn as you go. You're not forced to do this obviously but I thought I might aswell give the input now that the actual "problem" is fixed.
yeah thanks
this'll help me later on for other projects also
Also please never copy Unity's coding style because their style is a result of many years of supporting a whole different language and sticking to incredibly old conventions for backwards compatibility.
Just an FYI because I noticed that SerializeField wiki page already has some questionable guidelines
Hey everyone, is it possible to convert an instance of the MemoryCollection to json ? I seem to have issues converting the array, but it works on each individual element of the array.
This is how I save the data :
but in debug the json string is just equal to '{}'
Because you should not use JsonUtility
is it not reliable ?
It is perfectly possible but JsonUtility is too shit to convert even the simplest objects
alright then, do you know any alternatives ?
I suggest you download the Newtonsoft JSON, or JSON.NET Unity package and use that instead
The syntax to serialize with it is JsonConvert.SerializeObject
Okay, will do. Thanks !
Always useful to check out the Microsoft docs
No problem. To add, you need to make sure to use properties and not fields if you want to properly serialize everything
That wont work
System.Text.Json targets .NET versions not supported by Unity
You can support it, but this requires a lot extra work when Newtonsoft is a very good and popular alternative
Fair enough, i'll remove the link 🙂
Nah it's fine
To clarify, Unity runs with the .NET Standard versions since it uses Mono, where System.Text.Json targets specifically .NET 6/7/8 rather than any .NET Standard version
You need to mark stuff as serializable
Hello! anyone please could explain to me why I cant drag this Text (TMP) ?
Oh, I'll try that before switching then
You sure that's a Text Mesh Pro UGUI and not a regular Text Mesh Pro Text?
AH RIGHT, thank you.. on another note... i want this: when clicked on that cube/plane (well i switched to cube now, but in the pic it was a plane), i want it to be bigger, like, idk how to explain hence why I dont know what is it called to look it up on youtube (like the thing in games, 'press to inspect' then the item kinda is in the middle of the screen and looks bigger ot you
can anyone help me?
this code works with a regular camera but mousePos doesn't update when I move my mouse when I use cinemachine
fixed it! ^^
This is really bad to do.
Find is expensive
GetComponent is expensive.
Doing these in Update() is expensive.
Do it once in Start() and use Camera.main
@magic pagoda ☝️
doing it in Start caused aome issues for me
I have encountered the same problem before
Ill keep iy in mind tho
Figure out why and fix it, dont do what you're doing in Update() 🤦
I forgot how I solved it, maybe I didn't solve it at all.
I have multiple cameras so when I switch between them the code needs to recognise it.
Debug MousePosition
You should use a dictionary to manage cameras
Right, so then have a camera manager that fires an event and sends the active camera as a param, listen to that event and update accordingly.. it's not something that needs doing every frame
I solved it-
how solved
im confused:/
how to get image component?
拖过去
drag and drop
or if you want it done in code myImageRef = GetComponent<Image>();
yeah, drag and drop like I said..
:/
This is a code channel though, so if you're not doing it via code.. shouldn't be asking in here
i need help. few months ago i created 2d platoformer and now im back andthe player seems to sometimes slow down for no reason? the spead is still the same and it is multiplies by fixeddeltatime
scroll to the top, show the namespaces (all the using)
no need
i fixed ig
i asked cuz Image sprites and image component uses one name, i didnt know how to get component
Image sprites and image component uses one name
No they don't
"Image sprite" is Sprite and "Image Component" is Image
Neither of those are sprites
See how it says "(Image)" that is the type, it wants an Image component
wait, i need to use sprite instead of image?
This is a sprite.
If you want to drag a sprite from the project window into the field, then yes, that is a sprite
okay ill try
I asked this doubt before but i didnt frame it correctly so here we go again, In this flappy bird game, i want to increase the distance between the different spawning pipes to the right of one, not the distance between one pipe and the one below it if you get it? The code for pipe spawning is here: https://hastebin.com/share/desoqototo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
last time i asked this doubt i framed it wrong soo
increase the spawnrate
Works now thank you!
Fixed delta time? Show your !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.
Right, I must have mistaken the question in that case. As mentioned, increase spawnRate instead of heightOffset
I'm guessing this is not your code?
righto
trying to learn from another person
I see
How is this returning a null reference exception? shouldn't it just set the bool to false if it doesn't hit anything?
the code is not fine. read the docs on Resources.Load
At a guess, rune is null
my list with the runes clears itself on start for some reason
probably you have code that is clearing it
but also doesn't seem like it's being "cleared". Seems like the elements are being set to null.
assuming that's the correct line for the error
it is, I haven't set it to clear anywhere either
then you need to check what you have dragged into the List in the inspector
initialize that shit
showed it in a previous screenshot
it is null
you'd have to show the full script
that shows nothing
this doesn't tell us anything
bet he dragged the script from the project window
i'll send
Hey! what should I give to these so that this behavior stops happening:
currently when moving the marker, it can go inside the whiteboard, i want it to stop the moment it hits the surface if that whiteboard and not be able to go further
had it like that, changed it to see if that was the problem
Assuming they're not mistaken about which line that error is on, it seems like somewhere they're doing something like runes[0] = null;
you'd have to show how you're moving the marker
but typically you'd use raycasts for this
whats the site i put the code on?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
is Rune a monobehaviour
im using the XR toolkit
my suspicion is that rune.transform is null
i would use the debugger, and inspect the state of runes
as for the code to write its this :
the object might also be destroyed
you should move a proxy object with XR and have the marker move to a position along a raycast between the camera and the proxy object where the raycast hits
something like that
I added the runes = new list still doesn't work
you should debug.assert rune.transform is not null
make sure its null ref and not "object was destroyed but you are still trying to access it"
What does the debug log print?
seeing more of the code, i suspect rune.transform is null
what does Debug.Log(rune); print?
I would debug.log rune, then rune.transform
its null
the rune or the rune.transform?
Please give the actual exception and related stacktrace
Oh nevermind you just did
so show which object you are using to fill the List
answer the question, where is PlayerMovement script located, and where are the Rune objects located
uhm, any tutorial for it on youtube? im a beginner and i didnt understand at least 99% of that sentence 😅 😭 sorry!
what don't you understand?
When i say "proxy object" I just mean an invisible empty object
So, are you assigning this list in the inspector? Did you give this list a bigger size than what it actually contains? Because the remaining slots will be null
So you need to either make it the right size or ignore the null values
if you make the list in inspector, i don’t see how the rune itself can be null
Playermovement is on a cube that rolls around, runes script is on a rune thats a child of it
is playermovement in a prefab
You increase or decrease the list size but if you don't actually assign anything in the slot it will be the default value, which is null in the inspector
no
so all of it is in the scene from the start
this is it in the inspector
yeah, but he assigned the empty field in inspector
it exists
nope
is the rune null, or rune not null with rune.transform null?
Do you happen to have a second player movement script somewhere by accident?
do you have any other copies of this script in the scene?
transform can never be null
type t:PlayerMovement in hierarchy search
no, there is one other rune tho
it can if the transform is being manually assigned. we still don’t know if rune is a monobehaviour
I mean it must be a UnityEngine.Object since it's assigned in the inspector in the screenshot
the rune is null
yes, and you still haven't shown where that comes from
is rune a monobehaviour?
yes
then it is possible that the instance got destroyed
debug.log(rune is null);
this checks for true null
oh true
if i assign rune during runtime in ther editor it works
Turn on error pause in the console and see what's in the list when it throws the error
there's nothing in the list, it clears when the game starts
it does not 'clear', it replaces what you have filled it with with null
which is why I keep asking what do you fill the list with?
it holds runes that i assign in the editor, rune is just a gameobject with a Rune script attached thats a child of the cube that holds the playermovement script
did you try this #💻┃code-beginner message ?
add something like
private void OnDestroy()
{
Debug.Log("Destroyed");
}
to Rune
doesn't print
ok we excluded
- duplicate PlayerMovement
- Prefab/Scene serialization issues
- Nothing in PlayerMovement clears the list
- Rune is never destroyed
click the list variable and Find All References
Can you change:
public List<Rune> runes;``` to```cs
[SerializeField] List<Rune> runes;``` and see if any compile errors come up?
possibly another script is doing it
oh yeah Find All References would help here too'
should i be initializing it? doesn't work if i do or dont anyway
we're looking for code on other scripts that might be modifying the list
it doesn't matter either way since it's serialized
no, unity serializes it already even if you dont init it
unity serialization doesnt allow nulls by default
so thats the only references?
yes
error is the exact same
right i was looking for compile errors not runtime errors with that
anyway something isn't exactly adding up
are we totally sure you indicated the correct line for the error?
What's the current code look like vs the current error message? Which line number is showing?
change it to for loop and log the index and check the element one by one
log the transform as well
ie log everything
press pause in editor, then play, it will pause on first frame
check if list is null on first frame
since you are dealing with coroutines, lets exclude them as well
code and error
it prints destroyed when i do this but it also prints destroyed when i stop the game running so i think it just calls OnDestroy on pause
it shouldn't...
doesn't print destroyed when it isn't paused though
how the inspector looks like right after NRE?
type anywhere GameObject.Destroy(null);
right click destroy > find all references
go through everything and try to find some clue
it may be something that destroys all children of the cube, or some specific code that messes it up somehow
I want to create two prefabs using different instances of the same material, which should be reflected in editor mode for the artist to set them into the map. What is the proper way to do that without leaking, and without having to create two different material assets?
probably MaterialPropertyBlock
just do Ctrl+F and type it in there
hmm.. suppose you don't get the list of them in the window that way
and its slower
the only other one is in input actions auto generated by the input system
im just gonna make it so that the rune adds itself to the list when the game starts but thanks everyone who tried to help fix it
dont declaring anything as public next time...
as a last attempt to actually fix it, could you isolate the problem?
as best as you can, copy the thing to a new empty scene
if it works there isolated, duplicate original scene and start removing objects from it that can potentially affect it
Hey guys. I'm having an error while trying something I saw on a tutorial, can you help?
just ask
just ask us about your issue. post the error code and problem . . .
you spelled it wrong
in your code
(but correctly in Discord which is funny)
ok i tried the other way as well
what other way?
can't tell unless you show us . . .
If it still has a similar error when you spell it correctly SerializeField then you're missing the using directive as the error says
anyway it kinda sounds like your IDE is not configured
does the tutorial have the using statement at the top of the script?
you should set that up so you don't spend hours on silly little issues like this
Is your IDE configured?
yeah
tried with just the things that move the cube in a new scene and it still doesn't work, im just gonna do it how i said i can't be bothered debugging anymore
Are you getting syntax highlighting and autocomplete?
we know that part, it's what Praetor mentioned earlier . . .
ı tried it with two different IDEs
Sounds like it's not configured if you're not getting autocomplete
no no i just got autocomplete
i understand but as a consolation you managed to stumble on some rare edge case
i was typing so fast it didnt show that suggestion
now it did so problem solved thanks
thanks for trying to help
do you have any plugins?
can't even try updating the unity version cause i have to use the version installed on my universities computers
third party assets/packages
because that "when i pause it gets destroyed" sounds like some third party code
a font, skyboxes and a shader
work around it, but keep it in mind and keep your eyes peeled, the solution may pop up unexpectedly
I don't understand why I couldn't edit the polygon collider?
there should be a button next to it, try restart editor
editor bug
how do I fix this?
You don't. Report a bug to Unity, upgrade your editor, restart the editor, etc.
is this the only collider on the object? jw
that might be a bug. see if there is a different collider with its edit button available. Clicking one allows you to edit all colliders on the object. idk why they did it like this.
Bit of a random one, but is it possible to use objects as text? For example on screen score using objects instead of using text/textmeshpro ?
huh what for ?
you can do anything you want, you just need to create the text using objects. it must be done manually, though . . .
yeah, fixed it XD
GameObjects with TextMeshPro components are objects
so it's unclear what you're asking
Sorry, I mean using 3d Models. (just thinking ideas atm), ie, instead of using text/textmeshpro to represent the number 1 for example, use a 3dmodel of a number 1
TMP generates meshes for text, each letter is a quad, and it also exposes all that glyph data, which means you can map your objects to the meshes it generates, so it will take care of all the text stuff, kerning and whatnot, and you just have to align 3d meshes to the quads
yeah what's stopping you?
you can even extend TMP script and override its mesh generation methods with your own
Not entirely sure how to do it. lol.
I have a question about gameobject brushes. is there a way to implement rule tiles with a gameobject brush?
make a dictionary of char -> your meshes
for every character in the string, spawn an object with a meshrenderer and the mesh corresponding to the character
could use prefab variants too
Yeah I've got a couple of thoughts now 🙂 Thank you.
I tried doing raycast for mouseover function on a sprite. it worked. but once I used it on both sprites, they both mouse overed even though the mouse isn't there. how can I fix that?
Class A/Sprite A```C#
private SpriteRenderer objectSprite;
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if (hit.collider != null)
{
Color color = ColorUtility.TryParseHtmlString("#D2CCF1", out color) ? color : Color.black;
objectSprite.color = color;
}
else
{
objectSprite.color = Color.white;
}
}
void Start()
{
objectSprite = GetComponent<SpriteRenderer>();
}```
Class B/Sprite B```C#
private SpriteRenderer objectSprite;
void Update()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null)
{
Color color = ColorUtility.TryParseHtmlString("#D2CCF1", out color) ? color : Color.black;
objectSprite.color = color;
}
else
{
objectSprite.color = Color.white;
}
}
void Start()
{
objectSprite = GetComponent<SpriteRenderer>();
}```
instead of doing a raycast from each object - use OnMouseOver/OnMouseExit or IPointerEnterHandler/IPointerExitHandler
but the bug in your code is that it's only checking if your raycast hit anything rather than hit this object in particular
Also if you're doing a 2d raycast for the pointer like that you should be using Physics2D.GetRayIntersection(Camera.main.ScreenPointToRay(Input.mousePosition)
2d raycast is for rays from one point in the 2d world to another
Also why do you have two scripts that do the exact same thing?
Hey, I dont know if this is the right channel, but could it be that "Lobby" doesnt currently work?
wdym by "Lobby"? You need to provide some context. Is this a #archived-networking question?
Yes its thanks I go there
it....it worked...wow.. thank you so much man, been looking at this one problem for 2 hours straight
ah- I see the problem now..
Hi have a basic shader in which i wanna control the emissive map intensity withcode at runtime like 0 to 1 and 1 to 0 do any one know how to do that
note that this is for the Standard shader, the URP shader may have a slightly different name for that property
you can find the name with the shader inspector as shown
iirc you can't set it directly, you haveta do it through variables.
property is a method, a method will return you a copy of the struct
its explained on that page, but im pointing at it, its the essence of why you cant do it
yes, sadly
Vector2 test()
{
return new Vector2();
}
void test1()
{
test().x = 5;
}
position is an auto property of a Vector3, which is a struct. when accessing the property, it returns a copy, therefore, you cannot set any of the variables: x, y, z, for the property as they do not tie (exist) to anything . . .
no way around it until some new c# features arrive
Ohhhhhhkay so it's like the scope issues solved by passing by reference in c++, except in Unity the scope come from passing from game environment to script
no its purely c# issue with structs
in c# structs are copied by value by default
Okay I see now
yeah
still don't like that, cursed code, but at least I understand now
you can reduce it by writing it shorter
var tPos = transform.position;
tPos.x = 5;
transform.position = tPos;
you dont need to type out the type of swap vars
by default, structs are copied. if you change any field or property of one, you have to assign the entire struct back . . .
yeah I'll shorten it a lot in future. I named for clarity in the example so it was more easy to see, force of habit from a coding class
extension methods come in handy when dealing with structs, namely, position from Transform . . .
teacher was big on readable, understandable code, with or without comments
right you can use extension methods for that
what's that?
Hi! Question regarding transforms. Context is that I'm experienced with 3D math and graphics in general, but new to Unity. And the way transforms (we can keep it to translations) work is having me confused.
In other frameworks, including ones I've written from scratch, each model would have a transform matrix. If there's a parent relationship between models, the matrix would be multiplied with each parent to find final position in 3D space. This matrix data structure would be totally unrelated to the parent: if you have an object at an offset of (1, 2, 3) from its parent, and you reparent it, it would have the exact same offset to its new parent.
But this does not seem to be how Unity and GameObjects work. The translation of children seems to be very related to if the parent relationship was setup before or after the translation happened. I'm a bit vague here, but that's because I can't see the pattern. I've tried using both position and localPosition, but can't seem to find any logic in it.
Is there an easy explanation of how Unity transforms are supposed to work for someone used to simply having transformation matrices multiplied like I described above?
public static class TransformExt
{
public static void SetPosition(this Transform tr, float? x = null, float? y = null, float? z = null)
{
var pos = tr.position;
if (x.HasValue)
pos.x = x.Value;
if (y.HasValue)
pos.y = y.Value;
if (z.HasValue)
pos.z = z.Value;
tr.position = pos;
}
}
void test()
{
Transform tr = null;
tr.SetPosition(y: 5);
}
example of what you can do with extension methods
forgot to assign at the end
so essentially just, making a reusable function to automate the cursed bit? or is there something more I'm not seeing?
no thats it
Also why would it need to be static? I'm still learning when to use static and new and const and stuff like that
thats how extension methods are declared, in a static class
unity tends to preserve the position in world space
you maybe fan of unsafe collection since you can use pointer without get/setter...
I see, thanks for your help
the confusion comes from unity trying to maintain the offset for you by default
this is disabled by the optional bool parameter in most SetParent family methods
keepWorldPosition or something similar
editor tools, drag and drop have the same default behavior
with it set to false you get unmodified matrix
Ah, fantastic! Maybe that's the root of all my confusion! Looking good so far. Thanks!
I have a gun and a bullet. When the gun shoots the bullet, the bullet is rotated 90 to the left. I have tried rotating the bullet prefab, and changing the rotaton in code. Nothing fcking works please help
you'd have to show more details
is this a 3D object?
2d sprite?
Yeah
Your 3D mesh is likely exported/imported incorrectly
If you put it in the scene and set tool handle rotation to local - the blue arrow should point along the bullet's forward direction
Well yeah it shoots to that direction
But the front of the bullet is not facing there
yep
that's your issue
you have to fix the 3D model
you could work around it by giving it an empty parent which faces the right way - or re-export the model from blender or wherever with the appropriate settings
What if i downloaded the model and have no experience in 3d modeling
learn
I already mentioned a workaround if you're too scared to use Blender
they gave you a second option for a quick-fix . . .
ill try it ig
ty all
Uh i did that and bullets are not being shot from the gun they just spawn somewhere randomly
no clue why
you might be adjusting using center pivot maybe? hard to say without seeing anything
What can i shot you to make it easier
screenshot pivot from firepoint + send spawning script
kk
make sure the pivot mode in scene is visible 😛
currently writing something for this very issue
well the pivot of your projectile is very far
the pivot for your bullet is completely off . . .
Yeah ik
it should be at the base of the model . . .
And how do i do that?
all you have to do is parent it to an empty gameobject. Move the mesh until it matches empty pivot, then parent it
Light2D only has additive and multiply I just want them the circle light to stack over the other one, and I don’t know what to do
as Praetor mentioned earlier, use an empty GameObject as a parent of the bullet. move the bullet until it aligns to the pivot of the empty GameObject, then parent the bullet to the empty GameObject, or just use Blender and fix the bullet's pivot . . .
Fixing the model is always preferred, extra gameobjects have overhead
Like this?
still not corrent
unless ur in World Space (dont adjust pivots in world pivot mode)
Blue shold be where bullet points
Ah kk
much better, but not quite. the bullet should be facing the z direction (blue arrow) and the bottom should be aligned at the center axis (where all three arrows converge) . . .
So like the lowest point of the bullet should be at the moving thingy
just rotate the child bullet with X rotation until points with blue
do anyone know why i when i try to change a bool of animator in a private void it works, but not in a public void ?
there shouldn't be any functional difference
you have something else wrong and misunderstanding the issue prob
in the same funtion it can change a float in animator but not a bool, i don't get it
🤷♂️ you haven't provided code we can just guesstimate
Anything else?
private void Attacking()
{
if (_input.attack)
{
_animator.SetBool(_animIDAttack, true);
}
}
this works, when i change true or false
public void EndOfAttack()
{
_animator.SetFloat(_animIDAttackNumber, 0);
_animator.SetBool(_animIDAttack, false);
}
this doesn't works, only the setfloat works, the setbool is ignored
you probably have a nother function setting it at the sametime
this isn't the full context of the code
where do you call Attacking and EndOfAttack
etc
the animation calls it when it ends, the setbool is called nowhere else
hello!, do you guys have suggestion or some code for this one? i want to handle slope and curves when my character moves, my character using polygon collider 2D
After i aligned the bullet to its parent, it doesnt allow me to make bullet parents parent
Hey, guys! If I want to save my changes in settings on my game with a button for example Save or Apply how can I do that? I mean all my settings on my game.
What is the best way to handle damage?
Should the weapon subtract the health from a target?
Or should the target pickup the damage value from the weapon?
hello
I wrote a parallex backgorund script, but UnassignedReferenceException: The variable cam of ParallaxEffect has not been assigned.
You probably need to assign the cam variable of the ParallaxEffect script in the inspector this error came up
the weapon looks for IDamageable or something
passes its values how much damage it does etc.
To the IDamagable?
Currently what i was thinking, but was not sure what the best practice is
I have IDamageable fire an event
then things like health component sub to it and receive amount in the params
You probably need to assign the cam variable of the ParallaxEffect script in the inspector
Got it, that was the conformation i needed 😄
use a file like json or something
ı did but nothing change
you can put a json string in playerprefs if its only settings but don't recommend using it @sage mirage
there is also a limit on how much you can store in PlayerPrefs, so a file is better(imagine using cloud saving to port settings acrosss devices)
Either you didn't or you have more than one of that component in the scene
hello, i'm working on a tutorial but something got weird really unexpectedly, as i was editing a separate class and i got the error "Look rotation viewing vector is zero
UnityEngine.Transform:set_forward (UnityEngine.Vector3)" on this line:
float rotateSpeed = 10f;
transform.forward = Vector3.Slerp(transform.forward, moveDir, Time.deltaTime * rotateSpeed);
anyone got this problem and know how to fix it??
you must've rotated towards 0 at some point @pliant raptor
you can check if != Vector3.zero
iirc something to do with quaternions
Light2D only has additive and multiply I just want them the circle light to stack over the other one, and I don’t know what to do
i think it worked! thank you! @rich adder
