#💻┃code-beginner
1 messages · Page 281 of 1
yeah yeah understood
you’ll either give multiple Physics invocations before one physics sim, or you’ll miss the frames for input from Input
if you don’t split update vs fixed update
i get it now
Problem: Built a build with 1600x900 resolution
Built next build with 1920x1080. And it still launches as 1600x900 how to fix?
though lets say i detected that the player released one of the arrow keys, to stop the character from slipping i'm gonna add a force opposite to the force applied for meving the player. if i do this in FixedUpdate, using impulse, it's still gonna happen every fixed frame right?
Hey one question:
if i call a function in Update() Method is it possible that Update() is called again while i run the Method that i called in Update is still running? So will Update wait for a method that is called there or will it just call it every frame no matter what other method i called (I hope that this is somewhat understandable >:)
you need the if statement to make a check every frame
i belive you are referring to recursion
and you don’t want to set up recursion with Update
you would only want this with a custom method where you control arguments to know it will end
Hey everyone. I have this error, which I think means I didn't drag an object into my Inspector somewhere. But that doesn't appear to be the case.
Menu.Update () (at Assets/Scripts/Menu.cs:23)```
Can someone advise me on what to do?
This is what my Unity looks like.
Check line 23 of the Menu script to see what could not have a value
Menu.cs line 23 has an object that is null
that your code needs to not be null to function
Thanks both @short hazel and @buoyant knot. The error only appears when I go from Scene 0 to Scene 1. The Menu script is only attached to an object in Scene 0. It does not exist in Scene 1. Could that be the casue of the error? How do I go and prevent it? Appreciated! 🙏
Check line 23 and see what could be null on that line
From there you can investigate the causes
The input field which provides the text, which only exists in Scene 0.
that should be a serialized field
Well yes, if the input field is not also moved to the other scene, it gets destroyed when the scene unloads
That must be it. But why would a script continue running, on an object that's ALSO not present in the new scene?
The script is on an object in the other scene
Hm I must not be looking good at it then. Let me check again.
if the menu script is not in scene 1 why does it have code to go back to scene 0 ?
Search for it from the Hierarchy search bar, type t:Menu to filter out objects that have this script on
Oh my indeed! Found the object that also has the Menu script. Thanks!
Found it, thanks. That explains a lot. Already fixed the issue. Thanks a lot!
Can someone help? I wrote this code using the new input system. But at some random intervals, my jump won't seem to work.
public void Jump(InputAction.CallbackContext value)
{
if (value.performed)
{
// Check if the character is grounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
// If grounded, apply jump force
if (isGrounded)
{
rb.velocity = new Vector2(rb.velocity.x, vertical); // Set vertical velocity directly for jump
}
}
else if (value.canceled && rb.velocity.y > 0f)
{
// If jump button is released and character is still going up, reduce vertical velocity
rb.velocity = new Vector2(rb.velocity.x, rb.velocity.y * 0.5f);
}
}
Can you do .mp4 instead. .mkv requires a download
I suggest logging your session and make sure your states are being set correctly.
what other callback I should use to ensure my savesystem will happen
I also recommend just setting your desire to jump in the callback and handle things in fixedUpdate
Save every # minute coroutine
ahhh i set up the physics in fixedUpdate?
i actually have it already, just wanna make sure scumsaving is impossible 😁
here it is
what is it that cone thing that follows my player? How do I get rid of that artifact?
looks like you've added a light source to the camera target
I don't think that's the case
Hi, I am a new Unity user. I know that putting a collider for my mesh would make it stop from falling through the floor. I tried that but it still kept falling through. I also added another sphere next to my character with a rigidbody and a collider and notice how that didn't fall though but my character did.
click on the prefab and look in the inspector, and or open the prefab (double click it) and look there
it's not there
there's no lighsource attached to a players GO
do you have a collider on the floor?
look in the inspector, light is a component not a object
Physics should be handled in fixed update, yes. Now, in that video, is the issue still happening? I saw a couple times it seemed like you expected the jump to happen sooner?
You might want to use value.started instead of value.performed
I did have a mesh collider
I have is trigger off and tried both with convex on and off
still no
I'm not trying to be mean, but I'm gonna need to see an image of all 3 inspectors before I believe you 😅
I could be mean and ask if you are guessing or you know?
aighty, then you figure it out, gl 🙂
The light is pretty much dead center relative to the camera/screen so it's some component on the camera or something in the screen space at the very least (unless you've got this light object/component smoothly transitioning with the camera some other way)
It actually happens every time I land from a high spot.
can it be that terrain is metallic and just reflects the light like that?
It would imply there's a light pointing at the material from a very specific position.
whatever I change about my only lightsource, this artifact stays
Well, you only do the ground check when the Jump action callback is sent. I recommend doing that in update
You should also debug the state of things to get a better sense of what is going on
If you set the light inactive does it persist?
If so, that light isn't the culprit
if there's no light, that thing goes away, sure. But that would onyl prove the point that it's something with terrain material?
private void FixedUpdate()
{
// Check if the character is grounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
// If grounded and shouldJump is true, apply jump force
if (isGrounded && shouldJump)
{
rb.velocity = new Vector2(rb.velocity.x, vertical); // Set vertical velocity directly for jump
shouldJump = false; // Reset the flag after jumping
}
}
public void Jump(InputAction.CallbackContext value)
{
if (value.started)
{
shouldJump = true; // Set flag to indicate a jump should occur
}
}
I have, but sometimes it does not record the collision between the player and the ground
What is this cone thing that follows my player?
So you've identified that the cone following your player is from your light source. How you orientate your light will determine what kind of shape you'll get and how you modify your material would determine the intensity etc
It's quite obvious that there is a light component set to spotlight on the camera target or an object following the camera target. in the hierarchy, set the search to type, then search for 'light' all the lights in the scene should show up.
theres no tab for this - how do i get my convex mesh to stick to the mesh edges
happy?
More pro suggestions?
Hmm, the fact that it SOMETIMES works means the issue isn't necessarily with the OverlapCircle. Maybe put an else after the if in FixedUpdate with a debug showing the values of isGrounded and shouldJump
Just to verify the issue
set the mesh collider to convex, not a code question tho
My problem just got lost in the chat. I am just putting this hear to bring it back up. Could anyone help me?
Show the inspector for the player
Is that collider on the same object causing the gravity?
Looked like the root object was left behind on the ground, and only the child model fell?
not with that attitude, no
great. 1 less guesser
Here it doesn't detect the collision anymore
Alright, clearly is the grounded...
Can you show the groundCheck position child object?
Where did you place the log statement?
private void FixedUpdate()
{
// Check if the character is grounded
isGrounded = Physics2D.OverlapCircle(groundCheck.position, 0.2f, groundLayer);
if (isGrounded && shouldJump)
{
rb.velocity = new Vector2(rb.velocity.x, vertical);
shouldJump = false;
}
else
{
Debug.Log("isGrounded: " + isGrounded + ", shouldJump: " + shouldJump);
}
}
You don't, because that would be a concave shape.
Oh, are the PLATFORMS tagged as ground?
Well... yeah I saw you jump from a platform... so I guess they are
May as well check 🤷♂️
The groundcheck object looks like in the right spot
I have checked everything but I can't seem to understand where the problem is coming from
Thank you for your help. I am going to restart the project and try to trace my mistake
Does it only happen with that lower platform?
Nope
Seems to be fine with the floor and upper platform but it may just be a coincidence.
Wait, but the camera fell along with the child model.
this was a character controller in the unity asset store
it worked before
but when I switched scenes for a while and went back to it, this happened
Is the position of the player being set before the scene starts? Maybe the collider is intersecting the ground a bit when runtime starts and it falls through because of that.
But the camera falling with it doesn't really address what I said. I assume it would be a child of the model for positioning or track the model via code, right?
I tried moving the character up a bit, but it didnt work
Assuming the floor and player have got the proper components, what's in the player input script?
Are you perhaps moving with the Transform component or some other means?
This whole thing was in the Unity asset store
It worked a few days ago
but when I reopened it, it doesn't work
But I think it is transform
Maybe show the inspector for the floor if you haven't already or relink to it.
is this it
Yes it is and it looks fine. Were all of these components on the player starter asset by default?
Yes, but after this issue occured, I tried adding colliders to multiple objects hoping it will fix the proble
In the original video that I sent, I added a sphere with rigid body and it didn't fall though the floor like the character
Character Controller should come with a built in default hidden capsule collider already so no extra colliders should be necessary
Can you show the collision matrix?
could it be this thing, just yeeting the player through the floor collider? what happens if you set the strength to 0?
from the video it looks like there is a massive jerk down right as the game starts.
where can I find the collider matrix
Oh, let me try
The floor isn't assigned a layer so maybe you're pushing it downwards 
it only goes to 0.5
Unsure if push direction only applies to horizontal or any contact
oh
where is this?
prob unrelated if it's part of the default character rig, I just found the name a bit ominous 😅
That is what I thought at first too
What are the options for push layers?
You can google exactly where it is, but it's in project settings
It's no longer a concern if other forms of collision work - rigid body seems fine as you've suggested.
not the highest framerate in the world, but you go from this, to that in one frame on the video. what happens if you just place the player really high up?
So you placed it in the editor, but the first frame of gameplay seems to be SETTING the position lower
Do you have code setting the position?
It fell to the ground and when it touched the ground it was stuck for a second, but then it phased through
I am not sure. I will check right now, but my Unity is not responding
well that is wired! looks like it's hitting the ground, the phasing through it
So it does detect the collision
Thats odd
what if you just set this a bit lower?
it'll fall faster
...a bit higher 🥲
They probably meant moving the value towards zero 😅
like -5 or something
gravity isnt going to stop it falling through
check the collider isn't being disabled
Ok
I don't think so
Are you certain these are the correct initial components and settings?
but I attached a sphere next to the character and when the both fall down, the sphere actually hits the floor but the character phases through. But when I make the sphere a child of the character, they both phase through the floor
yea
something is doing movement without physics, possibly
with a ground check that's failing, not setup correctly?
if it was a rigidbody on the player then I'd say change the collision detection to continuous but looks like that player has a charactercontroller component
Try unchecking the player input and third person character controller component boxes - disable the two components.
I added a rigid body and tried that too 😦
darn
you sure you haven't got something in the script disabling colliders the player touches?
Its wierd that it worked before but after i switched scenes and back, this happens
yea
I would think you've changed something in between and have forgotten
turning it off and on again normally helps
Is it possible that a change in project settings resulted in this
but I guess not this time xD
depends what the change is...
if you changed something related to physics then yes, like the collision matrix or the step speed
but like if it was the collision matrix then it wouldn't be colliding first and then passing through, right?
it would just ignore it completely
yep
It animated hitting the floor so likely something else has happened and apparently it's fine with rb and a regular collider
maybe the collider is changing at runtime or something
maybe, but if the ground detection / animation stuff is just a raycast in the script, then it could be unrelated to the actual collision
ok yeah I guess so
Did you try disabling the two other components yet?
It's the Unity asset, so it's not code related.
Remove the asset and re-import it
Ok
I didn't try that yet
ok
eyyy turning it off and on again!
that should work
if that doesn't work, can you send an image of the collision matrix?
get into the package manager
find the folder and press delete
it's an asset from the store, not a package
wait you can't remove it from the package manager?
you can certainly import it from there
ah yes
I added some files to the folder so I am going to relocate them before deleting
my bad, I haven't imported an asset to unity in a long time xD
Yes.. but all the PM is doing is importing from a .unitypackage for store assets
yeah
That is safe right?
ofc
If they have code in, that references code in the asset.. you will get compilation errors after deleting, obviously
@short hazel @swift crag @buoyant knot Thanks all for your help today. I managed to create my working scripts, and can now succesfully input a name on Scene 0, and show it in the TextMeshPro that's displaying my score on Scene 1.
no luck
darn
Some things install as a proper package, going into Library/PackageCache
Most assets from the asset store will just be a .unitypackage (yes, great names here) that puts files in your Assets folder
yeah I know- I already knew that you couldn't remove the asset from the package manager, in the back of my brain... but I just forgor
ill try
programmers are so inventive with their names
bear in mind .unitypackage existed long before the package manager did
I used another asset for another scene and did another scene manually. Is it possible that the one I used an asset on messed with the physics
Your player was a part of the placement layer whereas the ground was set to the default layer
Placement layer seems to be unchecked with all other layers
Maybe set the player to the default layer instead of the placement layer?
how do I do that?
Is there any boxes I need to check
The players layer would be at the top right of the inspector for the player object
This was a problem I was stuck on for so long
In this clip, I only clicked spacebar once
These aren't really coding questions so it'd be more appropriate to ask them in #💻┃unity-talk
You'll get more awareness and suggestions. It would also be the proper place to ask for such a question without being off topic. Copy the message to the channel and delete the message here to properly move a message without cross posting.
and make a thread
Oh Ok thanks
My car interaction:
{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{{
using UnityEngine;
public class CarInteraction : MonoBehaviour
{
public GameObject player;
public GameObject carCamera;
public GameObject playerCamera;
public GameObject exitPoint;
public CarController carController;
public FirstPersonController playerMovement;
private bool isPlayerInside = false;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player") && !isPlayerInside && Input.GetKeyDown(KeyCode.E))
{
EnterCar();
}
}
private void OnTriggerExit(Collider other)
{
if (other.CompareTag("Player") && isPlayerInside && Input.GetKey(KeyCode.E))
{
ExitCar();
}
}
private void EnterCar()
{
player.SetActive(false);
playerCamera.SetActive(false);
carCamera.SetActive(true);
player.transform.position = transform.position;
player.transform.parent = transform;
isPlayerInside = true;
if (playerMovement != null)
playerMovement.enabled = false;
if (carController != null)
carController.enabled = true;
}
private void ExitCar()
{
player.transform.position = exitPoint.transform.position;
player.transform.parent = null;
player.SetActive(true);
playerCamera.SetActive(true);
carCamera.SetActive(false);
isPlayerInside = false;
if (playerMovement != null)
playerMovement.enabled = true;
if (carController != null)
carController.enabled = false;
}
}
My car Movement:
]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]
using UnityEngine;
public class CarController : MonoBehaviour
{
public float speed = 10f;
public float rotationSpeed = 100f;
private void FixedUpdate()
{
float moveInput = Input.GetAxis("Vertical");
float turnInput = Input.GetAxis("Horizontal");
Vector3 movement = transform.forward * moveInput * speed * Time.fixedDeltaTime;
Quaternion rotation = Quaternion.Euler(0f, turnInput * rotationSpeed * Time.fixedDeltaTime, 0f);
GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + movement);
GetComponent<Rigidbody>().MoveRotation(GetComponent<Rigidbody>().rotation * rotation);
}
}
My Player Movement:
}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
When I move my car moves aswell, also I wanna make it so that when I go up to the car and press E ill enter it, and the camera switch to the cars camera, and when I hold down E I exit and my player spawn on my Empty game object: "Exit" Can anyone help?
and my car flips alot, is there a way to not make it flip at all but still interact with other stuff?
Thank you
Ive never code before
!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.
Sorry, should have linked that to you before
CarInteraction https://gdl.space/medolonefu.cs
When you say "when I move my car moves as well" do you mean when you aren't in the car?
sorry Thank you
No worries!
yes and I cant get in the car aswell
CarMovement: https://gdl.space/siqaseriva.cpp
Ok one thing, it is VERY unlikely a GetKeyDown event will happen at the same time as the OnTriggerEnter event. You should instead have a bool that tells you that you are close to the car, then handle input in update
And yeah, you just read input in the CarMovement script without checking whether you are actually in the car or not
I am not good with these stuff not sure what you mean
Either disable that script when not in the car, or do a bool
Do not do input inside OnTrigger
Instead make a bool like
bool CloseToCar
And set it true inside the OnTrigger
Then in update, if that is true, and you press E, get in the car
For movement, you already have a isInsideCar bool
Just check that
if (!carInteraction.isInsideCar) return;
Right at the top of fixedUpdate
no, it's not ok to rely on chat gpt.. at all
don't cross post, delete it from #💻┃unity-talk
Definitely not, I don't wanna stick to just taking solutions to my issues from gpt all the time, as I come from non CS background and I need to elaborate the concern in my own words and try to get the best solution possible, I'm using any source available...
On the other hand, I find solution not at the every first attempt on gpt, I've got to drill in and get deeper and find the solution at times to get solution to complicated feature implimentation...
I'm also aware that how to Google is a skill and I believe chat gpt helps me in the same way...
hey guys, i cant add ne of my monobehaviors to any gameobject.
unity says it has compile errors, but there is nothing in the console, or the VS error list.
what do i do?
just don't code ur entire code-base from snippets of ChatGPT.. b/c then when theres a bug and you've stacked up snippet after snippet.. i can tell you 100% it won't be able to fix it for you
thats when people end up coming here.. and saying "whats wrong with my code" and its a dumpster fire
does the file name match the class?
how about just the file itself?
you can right click anywhere on project folder doesn't matter
no errors still
try adding script again
alr show the console / class + filename
well this is gonna take a while
console is empty other then some 'variable is not used' warnings
hmm are u sure errors aren't collapsed in console window ?
indeed
the counter on the top right also says 0
the one with the error icon next to it
Yes, I'm in the learning process and I'm trying to learn and understand as many concepts as possible during this journey and not in the mood to rush as well...
I break down the game mechanics to bit of chunks and try to get the solution for it on my own based on whatever the knowledge I've gained so far but if it's something new, I'm reaching out gpt to help me out and when the solution works perfectly, I sit down and go through those lines of code to see and understand what it means, how it works, and try to get every bit of knowledge out of it...
I also read that 80% of Senior Dev's find gpt most helpful, yet I'm not blindly gonna take that as final source of solution, I just wanna learn and get better and be job ready, so I'm trying my best in every possible way
Have you tried adding this script onto some other objects, re-open scene
thats b/c senior dev's have the know-how to spot and error and inform chatgpt of that error so it can re-evaluate the code.. the problem with beginners using chat-gpt is they can't usually spot when its being a dumbass
read that 80% of Senior Dev's find gpt most helpful,
where are you reading this crap though?
no, i will once 're-import all' has finished
oki
Relying solely on one resource like me for learning can limit exposure to diverse perspectives, interactive learning experiences, and hands-on practice necessary for comprehensive skill development.
straight from ChatGPT's mouth
but, its your learning experience.. so if ChatGPT is ur cup of tea, go for it.. just note.. that its against the rules to help you with AI generated code.. soo.. better not run into any bugs 😄
I agree, I'm here expressing out my concerns of using gpt since, I'm trying to figure out the best possible solution for the issues I face but I'm not completely relying on it as said before, my priority is not to use gpt and showcase my projects and when reality hits, feel lost, I don't want that, I wanna learn and get better in anyway possible and land my first job cuz of my hard work, I'm spending a day or two sometimes just to implement one of the simple features in the way it's supposed to work, so I'm here seeking help for better ways of finding solutions if there are than chat gpt
I did this harder
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ActivatinggameObjects : MonoBehaviour
{
// Start is called before the first frame update
private GameObject gameObject1;
void Start()
{
gameObject1 = gameObject;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Tab))
{
gameObject1.SetActive(false);
}
}
}
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
😄
this is nonsense
lmao, facts
Why?
it makes no sense
why are you creating a separate variable for something you already have anyway
gameObject.SetActive(false)
is sufficent
there is no reason to creating another variable to assign itself to it..
even the lesson doesn't do that, why would you do it 
I did it, I wanted to do it differently
lol.. well you did lol
gameObject1 = FindObjectOfType<ActivatinggameObjects>().gameObject;
ahh ofc ofc
Has anyone here played AirXonix PC game that was launched in early 2000?
ive played similar games
actually i played the 90s the 2D versions of them
some of them had naked chicks on it xD
as you cut the pieces you reveal more of photo haha
was a japanese game
I'm trying to build that game and so far, I've come close to getting basic gameplay mechanics and few other stuff, I want to know how to fill the empty space when I enclose it like in this game, not able to find the solution yet
I been trying to do this in 2D tbh because of nostalgia, haven't really thought about it in a while
you basically have to find a way to make your Verticies and create a mesh
Cool
yea so like each corner you turn , you make a new vert
then build the mesh when you completed
What about Raycast and Trail renderer, are they any help to make that feature happen?
You could use raycasts potentially but you'd have to probably make all your squares single boxes and might kill perfomance
Dang
try whatever is easier for you, then optimizing/iterate later
rely on math to fill them in
I once made a connect 4 game with nothing but raycasts cause it was too annoying to lerp math grid pos, it came out ok
u make a win / lose state?
yup fully functional, it just raycasts to check matching coins i each direction / diagonal
sounds fluffy
I spent whole day trying implementing some of the features, though I'm not successful upto the point of filling the empty space, I'm happy with today's progress of implementing some features for that game, I'll have it shared with you guys once it's ready if you wanna try and share input?!
Hey I am trying to make a flappy bird(ish) style movement system but it behaves very weirdly how can I make a movement system like flappy bird ish or how do I fix it Code:https://hastebin.com/share/buyuyomuve.csharp. Problem: Sometimes doesn't go up
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
once you're done post it in #1180170818983051344 with a link to webgl build or something
more likely you get plays with Webgl, i personally dont download any exe 😛
rb.velocity = Vector2.up * velocity * Time.deltaTime;``` you need to probably use AddForce to apply an upwards force when you touch..
Also, as you mentioned, I've faced Lodz of issues with webgl build on chrome, the game lags like hell on chrome WebGL but if I play it on Edge, it runs smooth as butter, any idea why it's happening?
strange considering they're both chromium based
maybe you have more plugins in chrome or something? are you sure its just u or everyone
I've very few plugins and extentions on chrome, a VPN, ad blocker, and another one or two but mostly all of them are disabled all the time
also you dont want to use deltaTime on rigidbody its already on a fixed consistent time
webGL lags like crazy for me on Chrome too
God, I'm not alone 😭
i swap over to edge or opera to play webGL games
Here is a video of the problem I am clicking a lot and I have tried changing the velocity
How about using Impulse than velocity for flappy, isn't it more suitable compared to velocity?!
Please forgive me for my dumbness if I'm wrong and educate me
like @rocky canyon already mentioned you should use AddForce, but also like I mentioned you should not have Time.deltaTime in rigidbody
soo smooth
I have tried add force it makes it so that it doesn’t go up at all (at least not noticeable)
then u just need to crank up the force until it does
lovely powerpoint slideshow
because u put time.deltaTime in it
I'm concerned about interviews, like what if the game lags for them if they want to play WebGL on chrome and if my games lag cuz of chrome issue and they reject me before even validating or checking 😭
ya, im running 2080ti too
so put a warning about Chrome browsers and put link to exe as option too
build ur games to Exe and put em on itch as a download
^ exe are OP.. just make sure to make ur page look professional with screenshots / video if necessary
so it doesn't look like a spam attempt
I've started doing the same and made sure to mention all the stuff in discription since I was worried 😭
Ok now I have another problem it goes up but I have to tap a lot to counter act gravity after it starts falling
turn the gravity down..
reopened scene, and tried a different go. still the same...
if you want consistent jump set the velocity = Vector3.zero before AddForce line
set ur velocity to 0 right before adding force
https://onepiecetechie.itch.io/brick-breaker
Is this okay???
looks fine to me
odd.. is just that script or others?
just remake the script w/ a different name
if it happens again u def have some compile errors hiding from you..
this script only
are there any other classes inside the script?
copy its contents, delete it and make new one
Vector2 or 3 I am using 2D so I assume 2
Oh btw the technique you want to look into to fill is called. Flood Fill
either one will work
unity just sets z to 0
its a 3D engine regardless
im curious on how storing information for online games would work, for example a players items
a server + database
On server side to avoid cheating
database or external files somewhere
Yeah that fixed my problem just have to adjust force now thanks
how do you reckon i aquire this so called server lol, cant you just use like a laptop or
i wont need it since its like 100 pounds so
internet speed is descent
probably something reliable, like the ones Unity has
you can def run a server on ur own machine.. i dont hear many ppl doing it
because its unsafe af (requires opening ports in your firewall / router)
also limited by your ISP bandwidth
theres free DB's out there
hmm alrr, can i also like get a database on that server?
unity gaming services
i use MongoDB
mongo is good too but its not safe to store connection strings inside a client so something with an SDK is better
Realm is good for Unity and interacts with Mongo
ya, i just use it to prototype for now.. just to learn how they work
alr alr, im just learning rn since like i dont rlly understand how servers work ig
then online is probably the last thing that should be on your mind lol
its pretty much a lesson for later on, start making something singleplayer and learn first
what about Firebase?
i know how to do singleplayer
but ive always wanted to do multi
don't we all
pretty good but their SDK is garbage for me its always buggy or not updated as frequent
Non-SQL are fun and quick to work with
esp in a gaming environment
sql is the easiest
its good to know
they all have free tiers
thats good
aws has servers too and databases
nice, so i presume databases store information that can be accessed by any client in code
well it gets tricky
you wouldnt want to store your DB connections directly in the client code
you need to interact with it through an API typically
yeah for sure, i would just referance it from the actual database instead of storing stuff no?
hence why pre-made solutions + SDKs exist like Unity UGS
mhm
because i wanted to use databases to store large strings that represent world data
and players can create worlds and others can visit them by typing in the world name
You can make multiplayer with just databases if the game is not exactly realtime
and the code can just create the world by finding the world data
think chess
for sure
but constantly updating player movement would be like
unoptimal no?
or
well you better have a server with lots of writes 😛
yee lol
You want to update as less as possible, thats why your client will try to predict where it might move before the server approves in a fixed update manner.
but this allows for example, if someone disconnects, the game can easily resume back or you can take "pauses"
p2p is not always the way
depends what game/project you're making
players will be in worlds and the game will only display players that are in the same world as you
and will display the world that you are currently in
by finding the world data
Maybe just look into some basic tutorials just to get the idea of how things are done in network for different types of games.
and everytime a change is made to the world, for example a player places a block, then the world data would have to be updated
You can easily test that locally first then scale to cloud
for sure
the concepts are exactly the same
i have tested it
but like
with databases
offline
on my computer lol
rather than on servers
server is just someone else's computer or yours ig
yeah
wouldnt be that much harder
ig
you would just have to referance another database
true
but yeah luckly unity has built in Auth and built in DB so its all connected
Kinda of a really abstract question, but... how do I make like arquing proyectiles?
Like they track a target but like something like this
arquing ?
oh like a parabola
Pretty much yeah
Ballistic trajectory
Sounds like a bezier math question
Wait, is this a thing?
It is called arcing in English
But that has mutliple meanings
Parabolic arc.
Or ballistic trajectory like I said
Those would be terms to research
In mathematics, a parabola is a plane curve which is mirror-symmetrical and is approximately U-shaped. It fits several superficially different mathematical descriptions, which can all be proved to define exactly the same curves.
One description of a parabola involves a point (the focus) and a line (the directrix). The focus does not lie on the d...
worked. ty.
I mean I am not looking for a mathematically correct parabola; I was more into like a random thing where it kinda arcs a little before hitting the target
Since I enjoy math, here's a simple example which you could use, with some modifications
Yeah, yeah I got that but I was thinking something more about the lines of... the proyectile does get a bit of upwards momentum before going full tracking, more than an actual formula for an animation between two points, cause the target is gonna be moving, so I think that would make the animation look really choppy
because I am struggling with this one
So you want like a lift up projectile which then starts to seek midair?
Yeah, kinda
instead of having players make lobbies in multiplayer, can you theoretically just have one lobby that every player thats in the game just automatically joins?
I would look into bezier curves then or you just split the animation into uplift and seeking codewise and just alter the timespan depending on the distance for example
Yes of course. More of a #archived-networking question
Why shouldnt it be possible? its just bad practice in terms of many players, because the amount of data to sync would grow quite fast
to solve that problem, you could probably just sync the players that are in the same world as you
i cant make lobbies as worlds since i want worlds to exist forever
in databases, that store their current state
well, that world would be a lobby still then
i could probably just create a lobby for the world if the world has 0 players in it
You should definitely be asking in #archived-networking
This is not a coding question, and certainly not a BEGINNER coding question
does that mean im not a beginner coder lol
its not related to coding because you dont have any code yet to talk about. its just theorizing about best network practices
No, it means the issue is not a beginner. I know nothing about you.
If you ARE a beginner, this question is probably too advanced
oh alr
Seems more of what I was looking for, but kinda hard knowing the position of the target is gonna be changing constantly...
you can always lerp to the updated position while processing the movement.
how do i find out where my code is getting stuck in a inf loop?
nvm, this is the last break point that was hit before unity stopped. any idea why im getting a inf loop?
here is FireFlechette():
private void FireFlechette()
{
int i = Mathf.RoundToInt(Random.Range(0, flechetteEffects.Length));
Transform muzzle = flechetteEffects[i].transform;
flechetteFireAudioSource.PlayOneShot(flechetteFireSound);
Vector3 dir = muzzle.position - (targetingSystem.hasTarget ? targetingSystem.Current_Target.position : transform.forward * 10);
Hunter_Flechette flechette = flechettePool.Get();
flechette.Init(dir, muzzle.rotation, muzzle.position, flechettePool, flechetteSpread);
}
what does flechette.Init do and do you do anything on get for the object pool
also are you actually certain that this is where your infinite loop is coming from?
i think?
also fireRate is 0 by accident, maybe that has something to do with it?
but then again. the for loop only does 6 iterations
flechetteBurstCount is 6
well then either the infinite loop does not happen here, or it happens in getting the object from the pool
do you know how i can exit the inf loop and exit playmode?
if you cannot break it using the debugger then you'll have to force close the editor
alr
its definitely happening here. when i comment this out, i no longer get stuck in a loop
show how you've set up the object pool since i've pointed out twice now that the issue is likely happening when you get something from the pool
also using unitys own pooling namespace btw
prefab is assigned
show the entire class for the flechette. and for the love of god share the !code correctly. screenshots of code are a pain in the ass
📃 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.
gee. whatever you say
class with the pool https://hastebin.skyra.pw/afaladesiv.csharp
flechette : https://hastebin.skyra.pw/evatobomor.csharp
yeah you have an infinite loop in Update
Well, it isn't what they say, it's in #854851968446365696
Using a while loop in update is often not right
ohhhhhh
shit, i wanted to put this in a coroutine.
thanks 🙏
ig ill just make the while, into a if statement
Update is already a loop, you probably could just change while to if
thats... what i said
Lagged. Last I saw was about coroutine
public class CoinScript : MonoBehaviour
{
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Coin")
Debug.Log("touching");
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
``` when I touch the coin it does not recognize it at all, it is not detecting collision.
{ } of the if statement are mission
what do you mean
valid syntax
they are assuming a compile error for some reason despite that being perfectly valid code
well mb
If(condition)
//I dont need {} for 1 line
put a log outside of the if statement to make sure OnCollisionEnter2D is actually being called
after you ensure that is working, fix your logic so you are not relying on object names and instead check a tag or for a specific component
exactly, he wrote it in 2 lines
wrong. thats 1 line underneath the if statement
yes guys I did the same thing couple hours ago and it worked perfectly, now it wont work with gameobject.name or gamobject.tag
I have the same code in the other script attached to player
and it recognizes the coin well
you def changed something, put the log outside if statement like boxfriend suggested
have you done this yet #💻┃code-beginner message
nope I dont understand what u mean cuz im completely new
Debug.Log
BEFORE the if statement
but it worked just few hours ago what is the issue now
well this is now, so u have to debug it
Then something changed
if you are so new that you do not understand what it means to put something outside of your if statement, then you should stop what you are doing and go through some beginner courses like the ones pinned in this channel
Maybe not in code
hey guys, why is the pool size 1, when its supposed to be 20?
pool is initialized in awake
where is it populated tho?
that is the default capacity that the stack used by the pool is created with. it does not automatically populate the pool with that many objects
oh... alright.
alright the collision works, I tried both with tags and names multiple times but its the same thing, it does not work
make sure that you are using the CompareTag method for checking the tag, not using .tag ==
my bad I fixed it
also when you put logs put something useful inside
something like printing the object tag and name of what u hit
i was adding tag to the coin instead of player ❌
That'd do it haha.
yeah idk, I made the script work fine and when i came home it doesnt work haha.
Debug.Log("touching");
Debug.Log($"{name} touched {gameObject.name} with tag {gameObject.tag}");```
which one you think would be more useful 😉
I get it but I was just checking if collider works because it worked in the past with the same script, I have just 1 player with tag so I do not need that specific debug
doesn't hurt to learn how to do it properly for next time
Like said before, the code is not the only issue. Can be how the name or tag is set up, what components are on there, settings in the rigidbody, positions. Never assume. Every time I do, I waste time 😂
I get it.
Ey lads!
I am trying to do a simple script to make an object to move towards the left side of the screen however there's this error:
NullReferenceException: Object reference not set to an instance of an object
ObstaclesMovement.FixedUpdate () (at Assets/Scripts/ObstaclesMovement.cs:13)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstaclesMovement : MonoBehaviour
{
private Rigidbody2D rb;
private float speed = 5f;
void FixedUpdate()
{
rb.velocity = Vector2.left * speed;
}
}
I think you might have to initialize rb. right now, its null i guess
assign
I will try
public class CoinScript : MonoBehaviour
{
public Rigidbody2D coinMove;
public float timerCount = 0f;
void timer()
{
if (timerCount < 2)
timerCount = timerCount + Time.deltaTime;
if (timerCount >= 2)
Destroy(gameObject);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Player")
coinMove.velocity = new Vector2(0, 1);
if (collision.gameObject.tag == "Player")
timer();
}
``` I have the function timer which says to destroy gameobject 2s after it has been touched, it is not working.
yes because u needtimer to add continiously which it doesnt do in a one frame event
skip all this, and just set a time inside Destroy's second parameter
how to write it in update
Destroy(gameObject, 2f)
you dont need to use Update for it
oh man, you mean destroy(gameObject, 2f)
It worked as intended, thanks guys ❤️
I have deleted the last if statement and did what you said, still doesnt work
you don't need the timer() method you created
just instead of calling timer()
show what u wrote
call the destroy with delay parameter
public class CoinScript : MonoBehaviour
{
public Rigidbody2D coinMove;
public float timerCount = 0f;
void timer()
{
if (timerCount < 2)
timerCount = timerCount + Time.deltaTime;
if (timerCount >= 2)
Destroy(gameObject, 2f);
how did i know you would write it like this..
if you already made a 2 second timer from destroy , why did you keep the rest of broken "timer"
idk man Im new
skipp "all this" meaning all the code in timer()
and just do Destroy(gameObject, 2f); where you need it..
public Rigidbody2D coinMove;
public float timerCount = 0f;
void timer()
{
if (timerCount >= 2)
Destroy(gameObject, 2f);
}
``` like this?
no not at all
why is timer still here
why is destroy in a float that never increases
cuz im not u
like i said already, all the code in timer() isn't needed.
just use Destroy with the timer it has, where you need it..
if (collision.gameObject.tag == "Player")
is it better to use a rigid body or a character controller. Also I;ve just tried adding a jump force and for some reason it counteracts all other forces and stops moving horizotnal.
Hello, I have a little issue blocking me on my way to realize a QTE, it's the last step I'm struggling one :
I want to be able to use the new input system into an "OnTriggerEnter2D" method, though, it's not working...
Here is the code of everything I declared (for example variables)
public GameObject objectToRotate;
public GameObject pivotPoint;
public int rotationSpeed;
public GameObject[] zoneQTE;
public int currentZoneQTE;
public PIA playerInputActions;
private void Awake()
{
for (int i = 0; i < zoneQTE.Length; i++)
{
zoneQTE[i].gameObject.SetActive(false);
}
currentZoneQTE = Random.Range(0, zoneQTE.Length);
zoneQTE[currentZoneQTE].gameObject.SetActive(true);
playerInputActions = new PIA();
playerInputActions.PlayerInput.Enable();
}
Here is the code of the method
private void OnTriggerEnter2D(Collider2D collision)
{
if (playerInputActions.PlayerInput.QTE.triggered)
{
Debug.Log("Hello world.");
}
if (collision.gameObject.tag == "zone-qte")
{
if (playerInputActions.PlayerInput.QTE.triggered)
{
Debug.Log("Hey, QTE has been succesfully done !");
zoneQTE[currentZoneQTE].gameObject.SetActive(false);
currentZoneQTE = Random.Range(0, zoneQTE.Length);
zoneQTE[currentZoneQTE].gameObject.SetActive(true);
}
}
}```
I've tried many things and the new input system is working I'm calling an input into the update() method, it's really calling an input from the OnTriggerEnter2D which is creating issue...
Don't hesitate to @ me ! :>
I dunno what a QTE is, but since this involves an input, are you sure you wanna do it in OnTriggerEnter?
That means it'll only check when you initially enter the collider
What should I use according to you ?
QTE stand for QuickTimeEvent, it's those little interaction you can have on screen when doing some actions !
OnTriggerStay, i guess
In my case, I want to do kind of Dead By Daylight like QTE ! If you ever played the game ? ^^
Wait
No :/
What is this ? It's like onTriggerEnter but all the time where it's triggered ???
I didn't knew !
I'ma try that !
hey guys how do i make it so that buttons aren't clickable only selectable by arrow keys
To make it quick, in dbd when you repair generators for example, there is a circle popping on the screen with a cursor rotating around it ! when the cursor's hovering a certain zone of the circle, you gotta press your keybind ! ^^
Ooooo ok
Yeah i think you need OnTriggerStay, to constantly check while it's in the zone
huh?
oh, yeah...
@elder locust i'm curious, did it work?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObstacleSpawner : MonoBehaviour
{
private float time = 0f;
private float spawnDeltaTime = 1.5f;
public GameObject obstacle;
[SerializeField] float height = 1f;
[SerializeField] float offset = 5f;
void Start(){
obstacle = GameObject.Find("Obstacle");
}
void Update(){
if(time > spawnDeltaTime){
GameObject go = Instantiate(obstacle);
go.transform.position = new Vector2(offset, Random.Range(height, -height))
time = 0;
Destroy(go, 10);
}
time += Time.deltaTime;
}
}
Sorry.
It worked but it strange, it's working but not all the time... :x
hi im experiacing a syntax error and i cant identify it, its on line 34 from what console says
Maybe show the error from the console
is grunt_gun a data type or a name?
folder
yes this is wrongly defined method
You'd require both for the function signature
it looks like you are making a param of type Grunt_gun and not giving it a name
@vale geode need to configure their IDE
I created an svg (300x300 pixels), added the com.unity.vectorgraphics package, and dragged the svg to a game object. It gets displayed but does not fill a 300x300 gameobject.
What's a 300x300 gameobject in pixels? is the value of height 100 equivalent to 100 pixels?
thank for your hellp everyone
did you configure your IDE?
i didnt figure out how
!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
make sure you do it, its requirement to get help here
And it is just way easier to code when it is configured
what database do u use lol
huh? I don't strictly use one lol
oh lol i thought u mentioned u used one
Odd question, especially with the lol at the end
Strictly meaning ONLY one. Nav uses multiple
also strange to send that on that reply to someone else
If you need recommendations, we can suggest some. Depends a little on the game, but often JSON and Binary may be a better fit
Databases? I just ask the user to remember the state and have them fill in a form before each game
Why change when the initial solution worked fine
Guys I got this from chat GPT asking for a editor tool that assigns prefabs in a folder to a list, but I and like veeeey confused with the part that treats the folder as a GameObject, is that a thing?
Wat? Where does it treat a folder as a gameObject?
Oh, the class field. Didn't notice that.
Don't ask a text generator to generate meaningful text
it doesn't know anything, and there are multiple nonsensical things it's written
and I'm not going to fix them, because it's against our conduct to begin with
This is exactly what I'd expect from gpt lol. It saw "prefab" and probably took a hint from the hundreds of bad tutorials that all use GameObject variables with prefab in the identifier and just ran with it
- • Posting unverified AI-generated responses or failing to mark AI-generated content as such.
Yeah, but I did mark it as such, I am not posting it as veridical, is just a base to work with
Is that wrong?
It's unverified because it doesn't work
We're not here to correct the mistakes of autocomplete
If you haven't verified that it works, then it's not allowed here
Hi, I have used a unity asset which automatically disables the cursor once I click start. Is there any script I can use to bring it back?
Ok... but... if it does work what I am even supposed to ask then?
thank you I will check
And also, when I load a new scene from another scene, my materials for my object disabled. However, in the actual scene, it is still there. Is there any solution?
You can include AI-generated responses as answers if you've verified that they're true. Though, people may still be hostile to it because it's irritating behaviour
Ok, well scrapt that how do I do this from scratch then? How can I get reference to an entire folder and its children?
materials can't be disabled
they're just assets
But it shows all black when I load a new screen
what is it supposed to show
That is happening for reasons that do not include a material being "disabled"
Let me send a video
I have a question about DeltaTime
so I'm moving the character controller with this:
controller.Move(playerVelocity * Time.deltaTime);
but then in another part of the code im doing this
// Friction
...
playerVelocity += fric * 0.01f;```
do I need to multiply these too, even though im already multipliying when I move the controller?
how do i declare a ref int pre c# 11.0
maybe? Depends exactly what that other code is supposed to be doing.
it gets multiplied in the Move function
what other code
and praets right.. it depends on where ur +='ing
Are you trying to add fric per second? Or are you trying to add fric per frame?
The second snippet
this is the issue
the spaceship is black when I load into the next scene
wheres the lights?
but in the scene itself, it is alright
im not sure, I'm just trying to add it. basically I have playerVelocity, and this is moved by the players inputted direction and then by friction, which is a vector that is opposite to it and some fraction of its magnitude
I'm not specifically trying to add it per second or per frame, I wouldnt know the difference
pause the loaded scene and find where your lights are..
if that code runs in Update or the function is called from within update.. its probably per frame
no need its a CC.
so u probably want to use deltaTime on ur += lines too.. since they run in update im about 73% sure.. and then you can modify the values to take in consideration the new multiplier
hmm ok
honestly I wonder if that factor I have is just to account for the fact that it's not there
I propably realized it felt way too high
im HOPING that a lack of deltatime is why the movement feels very slightly but subtly off in weird inconsistent ways
Hi, I looked at the lights
it'll get higher once u multiply deltaTIme
I wasn't able to find it
im thinking when I spin around too fast it drops the frames and this causes an issue
ya, where do they go? 😄
why would u have lights in the scene if u run it stand-a-lone.. but when u load into it they dont..
🤔 thats the question
Let me try searching for it in the actual scene
one good way to test (imo) is scale ur game-view window really small.. and then fullsize.. (when its very small ur frame rates will go really high) and then you can usually tell a difference (or when ur values need to be frame independent)
It works right now because I just included lights
Thank you
👍 no problem
But another problem is that when I load in to the next screen, my cursor is hidden. What is the simplest way to unhide it
put a script in that scene that unhides it in Awake()
Can I not make GetFiles() search in cascade in its own subfolders?
Cause I cannot find that
Use the overload that has the options to do that
Right now in my game, I have a placement system which places exactly at the mouse position, but as this requires really steady hands, I want the placement to be more grid locked, how could I go about doing this? My current script instantiates an object in the exact mouse-world position. Thanks
I recommend using the built-in Grid component.
is it complicated to implement
It has methods that will let you easily convert a world space position to a grid position
no
thanks ill check it
As an example, using a grid, you would do this to get a locked grid position for a given mouse position:
Vector3 mouseWorldPos = whatever;
Vector3Int gridCoords = myGrid.WorldToCell(mouseWorldPos);
Vector3 roundedPos = myGrid.CellToWorld(gridCoords);
// OR
Vector3 roundedPos = myGrid.GetCellCenterWorld(gridCoords);```
depending if you want the grid centers or the grid corners
yeah seems easy
The nice thing is you can set the grid up exactly as you want from the editor, including cell size, cell shape, scale, position, rotation, etc.
and you don't have to worry about that stuff in code
I have one function which gets the mouses position, this is used in about four scripts. Is it better to make a separate script which just constantly executes that function and the function is accessed from that one script?
Rather than executing it upto three times simultaneously from each script
How the hell is this returning out of range exception?
pool.Count is 0
anyone?
also .Count is the total number of elements.. so if u have 3 elements.. it returns 3.. but there is not a 3rd index.. theres only 0,2,1 so u need to - 1 to get the last index
no
-1 is not needed
Random.Range is exclusive of the top end for the integer version
oh shit yea u right..
i forget about that
That's really, really unlikely, but it seems it did happen indeed
It's the only way you would get that error here
lol, anytime im wrong or get called out i write it down on a post-it and stick it to my wall
Ok, that shouldn't be a problem as I add more stuff and confirms that my tag to make some items only spawn once does work
So it is actually good sign XD
You should validate the random int and just not get the index if it is 0
Handle errors gracefully when possible
sry I was away for a while so I couldn't respond. But how exactly would my script look like? Sry, I am a new user
is this a good idea?
defensive programming would indicate you should do something like:
if (pool.Count == 0) {
throw new Exception("The loot pool is empty!");
}```
or handle it in some other way
using UnityEngine;
public class ShowCursor: MonoBehaviour
{
private void Awake()
{
Cursor.visible = true;
}
}```
It should never ever be 0 once the game is complete. But in case it happens what should I even do here?
Tell it to roll for a different item?
A helpful error message like: #💻┃code-beginner message would be better
Is that possible? If you have some reasonable way to recover from this state, you should do it.
"Should never" is something you should never say or think as a software engineer
edge-cases wants to know ur location 😄
Beware of creating other problems though - like an infinite loop
The scary part is that Random.Range is inclusive with floats
I have code that absolutely expects it to never return 1f
Your 10 millionth player has a surprise waiting for them!
well, it does at least bail out with some kind of vaguely acceptable result
Free car!
Also wrong sound effect
throw new Exception("The loot pool is empty!");
does this show a debug log? and/or stop the game?
i have a spare project open.. imma just test it 👍 need to figure it out anyway..
you could do Random.Range(min, float.BitDecrement(max))
oh that's neat
I've thought a few times about being able to do that
ahh, so it throws an error but doesnt stop the gameplay.. nifty
lol.. i should handle more errors too.. (but i dont expect any errors) 😅
It will stop the current code execution in its tracks - up until the nearest try catch block (or the Unity Engine if you don't have one)
if im calling a function from another script, how do I call a variable that the function returns
actually the issue is.. i dont know when a situation would cause an error that i would need to be weary of..
Assign it to a variable
Not quite sure if this could create a endless loop, seems like it?
For example:
float ex = myRef.MyFunctionThatReturnsAFloat();```
Does ChooseRarityPool() call this function?
If not, then no it can't cause infinite recursion
the variable before the function?
It just chooses one out of 5 lists based on chances
you could use MyFunctionThatReturnsAFloat() anywhere that a float is expected
The = operator means "Assign the value from the right side into the variable on the left side"
Though this could still return out of range exception, just even more unlikely
then no, basically all this code would do is give you one extra chance. There's no guarantee that one would work though
How could I tell it to keep trying though?
maybe you should have it only select loot pools that have at least one item in them?
I want to access the mouse position from this script in other scripts. if i want to access the always changing mouse position, would i call it in the update function of the other scripts which call this function?
I mean the idea is that all pools should have at least 3 items that can always spawn, just that they are not implemented yet
ive never found a good solution for this..
ive had the same issue when trying to find a random number.. say the number doesn't work? do i try to run it again?
and what if i do run it again.. and the 2nd number doesn't work.. do i run it a 3rd time? lol
just put some placeholders in then
you should just make that second function static
get rid of the Update
and get rid of the field
which field
so id call it in the update function of the other scripts accessing the function?
public static class MouseHelper {
public static Vector3 GetMousePos() {
Vector3 mouseWorldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mouseWorldPos.z = 0;
return mouseWorldPos;
}
}```
basically
doesn't need to be a component at all
doesn't need any fields
or storage
just call the function
bruh ive never seen that
Yeah, that should be a thing in programming, you keep repeating until you don't get an exception XD
Camera.main doesn't need a Monobehaviour?
it's static
like this?
Camera is not a property of MonoBehaviour, yes
Yes then in another script you just do MouseHelper.GetMousePos()
do i need to drag anything to reference it?
nope
nope
this class doesn't even define a component, so no
interesting
it just works.. as long as its in ur project folder
only components are attached to game objects
does it need to be in the hiearchy?#
nope
and only classes that derive from UnityEngine.Object even matter in unity's eyes
you can do whatever your heart desires with a class that doesn't derive from UnityEngine.Object
whats that kind of script called (need it for my documentation)
Static
You may call it a "plain old C# object" (but this class is fully static)
static script?
so...plain old C# class, at best?
POCO
you can't have instances of a static class, so it's a bit weird to say it's a plain old object :p
plain old is the actual name?
You can really just call it a .. class
that's it
it's a class
you've developed some preconceptions here!
Hi, I tried your solution. I wanted the cursor to show in the newly loaded scene. However, the cursor was locked, and I wasn't able to interact with the button. Is there any specific place to insert that script because I currently put it in an empty object.
fr
the rules that apply to MonoBehaviour (a kind of component) are not universal
Unity just has some special rules for its own kinds of classes
if u mention Poco, advanced programmers will know what u mean but yea, its just a class that doesn't derive from Monobehaviour so it doesn't need to be on a GameObject
i just ignore everything above my variable initialisations
yeah ill put poco in brackets
well if ur Controller hides and locks the cursor u'll also have to unlock it..
In my controller?
Cursor.lockState = CursorLockMode.None;
no in the awake of that new script on ur new scene
its locked b/c ur Controller from the previous scene locks it
just like it hides it
so.. just add that line to the awke and it will be visible and unlocked
when the scene loads
sorry how do i call it?
yes u need both
Cursor.visible = true;```
Oh, Thank you
You have no class named MousePos
woops your rigfht
You named it MouseHelper
Oh, that's nice, I didn't know about that met- 😔
and if i want to call the returned mouseworldPos variable?
and you dont call it per say.. u just access it when u need to assign it..
Vector3 mousePos = MouseHelper.GetMousePos();
yes, thats what its returning
Yea it worked. Thank you so much
yeah how do i access it
MouseHelper.GetMousePos();
if you debug Debug.Log(MouseHelper.GetMousePos()); it will show u a Vector3
I do need it to be called in an update function though, so could I do that in the static class or in the scripts
if that terminology is even right
Vector3 mousePos = MouseHelper.GetMousePos();```
put it in a variable, as mentioned earlier
you just call it whenever you need it.
yeah i get that thanks
but i need the fucntion to be in an update function
so would i edit that in the class
Huh>>
and how? Cause im unfamiliar with doing this static class thing
the mousepos needs to be updated constantly
void Update() {
Vector3 mousePos = MouseHelper.GetMousePos();
// do whatever
}```
no it doesn't
how comes?
you just call the function when you want the current mouse pos
Like this
okay ill try that
'MousePos' is missing the class attribute 'ExtensionOfNativeClass'!
anyone know what this means
yeah you have it attached to an object
remove it
alr
Could any of you guys help me with an issue I'm having with my layout? I have a prefab that has child GameObjects TMP Text, and Buttons. They're the child of my content GameObject, and I just cannot get this thing to set each prefab's size according to the text component. I can send more pictures if needed
woah its working
I feel like the "+1.5" in the line 107 isnt delaying anything, as soon as all them agic balls are in palce, they start moving towards player, but the first magic ball never has the slight delay im looking for. What am i missing here?
Mage script: https://gdl.space/xifefetuti.cs
Magicball script: https://gdl.space/lehamurudi.cs
as im using c# to code my game, are the functions im making functions or methods?
both
typically in c# the terms are interchangeable. but technically they are all methods
a function in a class is a method, but a function outside of a class is a function (i think) 
is every variable called an attribute then?
like oop
no, attributes are something different in c#
pretty sure only java calls class-level variables attributes
glad microsoft doesnt :p
this explains it well ofc
https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/
Unity also has a couple of useful ones too. https://docs.unity3d.com/Manual/Attributes.html
I'm using an animation to upscale my gameobject from zero, but this causes it to get stuck into other objects sometimes 
Is there a way to make it redo its collisions or should i use some janky fix like spawning a fullsize game object after its animation is complete? 
are those rigidbodies?
Yeah
thanks
Yeah, i'm just scaling the entire object 
Thank you so much for the info 😊🙏
I'll give it a go, thanks! just set up a coroutine to run with it when collision happens after a few seconds
will see if it gets fixed 
sure yeah lmk how it works out
seems to work, stuff gets pushed out 
id start with that error.. assuming you want to get a random number for your~~ _creatures GameObject[] ~~ (should be a List<> if you're using .Count) you could replace list.Count with _creatures.Count that would store a random number that falls within the bounds of ur array
then you could enable that creature
it appears that each creature disables itself on click.. and calls the gameManager's CreatureClick() function to enable the next one
do you have a specific question here? You have a compile error in your code, you should probably fix that.
After that, think through what you want the script to do step by step, then get to work writing it.
arrays don't have a property called Count
Is there anyway to have the Custom Debug open the SandboxControl script.. such as the Unity one does.. could I pass in context to the custom static debug?
I can pass in context to highlight the gameobject but it still opens the static class
thank you, i'll check it out right now
ohh neat, this is exactly what im hunting for
aye!
double click still opens the static script.. but atleast now the actual script and line number is visible in the log w/o scrolling so I can just click it instead
How do we make a State Machine with a generic State like
public class StateMachine<T> : MonoBehavior where T : State
and also make StateMachine known to the state like declare its statemachine owner?
Not sure if this is what you mean but maybe this will help
https://stackoverflow.com/questions/41876683/classes-coupled-with-each-other-by-generics
I think you would need to use an interface here
Using a generic here doesnt make a whole lot of sense imo, because you dont want a state to inherit from a state machine. The states exist by themselves, the statemachine controls when they are used
Nothing here makes State inherit from StateMachine though 🤔
hm i assumed the states would be made like
public class StateName : StateMachine<StateName>
but still, the existing generic makes it seem like there would be 1 state machine per state
At least to me, I dont see the use of generic here
I was thinking more likecs public class StateName : IState<StateMachineName> If they want the state to know about the machine
But it's not necessary
why would the state need to know about the state machine though? that relationship should really only go one way
i wonder that i always find a hard time implementing something with delay
private void CheckAndUpdateGoblinEmployment()
{
// Ensure GoblinCollection reference is set
if (goblinCollection != null)
{
// Get all child game objects of the GoblinCollection
foreach (Transform child in goblinCollection.transform)
{
// Get the Goblin component attached to the child game object
Goblin goblin = child.GetComponent<Goblin>();
// Check if the Goblin component exists and the child game object is inactive
if (goblin != null && !child.gameObject.activeSelf)
{
// Set the isEmployed variable to true
goblin.isEmployed = true;
// Start a coroutine to activate the game object after a delay
StartCoroutine(ActivateGameObjectDelayed(child.gameObject));
}
}
}
else
{
Debug.LogWarning("GoblinCollection reference is not set in GameManager.");
}
}
private IEnumerator ActivateGameObjectDelayed(GameObject gameObject)
{
// Wait for 2 seconds
yield return new WaitForSeconds(2f);
// Set the game object to active
gameObject.SetActive(true);
}
if the gameobject is set to active false set variable isEmployed to true then set active to true after 2 seconds delay
some of my old codes requires the states to transition to another states internally
maybe i should just do that in statemachine
I dont think that's good design.
Personally I don't think states should know how or when they transition.
i dont really want to make a dictionary for possible transitions for each states
Why not?
my new code have pre-initialized components, constants and only resets variables on enter. the states transition by a bunch of ifs
in controller of course
The way I would do it is have the StateMachine hold a Dictionary<State, List<Transition>>.
The StateMachine can have a method...
public void AddTransition(State from, State to, Func<bool> condition)
In the function create a new Transition which holds all these variables.
When you are building your state logic, create all your states, set up your transitions, toss the state machine an initial state, and then it just goes.
Separating the logic of a state from the transition allows you to rewire it much more easily.
Otherwise adding new transitions requires you to constantly toss references between states.