#💻┃code-beginner
1 messages · Page 620 of 1
isnt counter clockwise the normal way?
let me reverse it and check
i think its because
what do you get when you reverse
Vector2.SignedAngle(Vector2.right, directionToGhost)
well it returns a value between -180 and +180
never anything beyond that.
So if you want to translate that [-180, 180) to [0, 360) you need to do like:
Vector2.SignedAngle(Vector2.right, directionToGhost);
if (angle < 0) angle += 360;```
this seems to sometimes(?) work, im testing with multiple enemies and it seems like if they come from the front it stops working
stops working how
like what happens
also what is the end goal of all this?
What are you doing with this angle value?
as in it gets the wrong angle
Can you show the code, a screenshot of the scene, and what angle it's returning?
And what angle you expect it to return?
circling the player, normally id use an easier method but i have weird movement/velocity system that makes it a little more complicated
sure
How does this have you circle the player?
by increasing the angle every frame
im trying to grab the initial angle
so wouldn't you be driving the angle from a variable here instead of calculating it from positions?
I see
the first image is getting the initial angle when the enemy enters range, the second is using it (and increasing it) to set position
Are you intentionally doing =- there?
for testing purposes bc it wasent working without it before, yes
that's the same as just =- x is just the same as = -x
there isn't really a thing of =-
oh you meant that
mistype
btw when i was saying the actual angles, it was from the print, not after it decides its position in the second image
Is current angle converted from deg to rad anywhere?
Also sin(0) == 0 whereas cos(0) == 1. At 0 degrees, it should be (1, 0) and right now you have (0, 1) because you swapped cos and sin
Also you could just do this:
Vector2 initialOffset;
float rotationAngle = 0;
void StartFollowing() {
rotationAngle = 0;
initialOffset = transform.position - player.position;
following = true;
}
void Update() {
if (following) {
rotationAngle += Time.deltaTime * rotationSpeed;
Vector2 newOffset = Quaternion.Euler(0, 0, rotationAngle) * initialOffset;
transform.position = player.position + newOffset;
}
}
does it need to be converted into rad? isnt sin 45* persay like sqr2/2, just as sin(1/4)r?
Sin accepts radians
(and cos)
so yeah if you want to feed degrees in you need to convert
oh
also yeah your sin/cos are reversed for x/y as foo said
And you can avoid all that by just rotating the initial offset vector with a quaternion like in my example
Hello, is there a way to make a conditional public variable? Like if a certain condition is met, then the variable shows up on the unity editor.
Not without a custom editor or a plugin
Here's a popular free plugin that does it: https://dbrizov.github.io/na-docs/attributes/meta_attributes/show_hide_if.html
Will check it out, thank you!
public async Task<string> PerformApiCall(string url, string method, string jsonData = null, string token = null)
{
using UnityWebRequest request = new UnityWebRequest(url, method);
if (!string.IsNullOrEmpty(jsonData))
{
byte[] jsonToSend = Encoding.UTF8.GetBytes(jsonData);
request.uploadHandler = new UploadHandlerRaw(jsonToSend);
}
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
if (!string.IsNullOrEmpty(token))
{
request.SetRequestHeader("Authorization", "Bearer " + token);
}
await request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
return request.downloadHandler.text;
}
Debug.LogError("Fout bij API-aanroep: " + request.error);
return request.error;
}```
Why does this code work in the windows build, but not in the web build?
oh sick that worked. could you explain what Quaternion.Euler does?
it creates a quaternion that represents the rotation given by the set of euler angles you pass in
in this case "A counterclockwise rotation on the z axis by rotationAngle degrees"
i have not reached that in math class 😭 ill look into it. tysm
this works fine in the windows build and in the editor
how do I move the canva? it is way too huge for my game sizes and I can't seem to be able to move it
because its meant to size with your screen , you don't move it
also not a code q
a what?
The way the canvas is drawn in scene view has nothing to do with "size" of it. It is always the same size as your game resolution.
but look where the camera is
(not a code question)
yes the UI is not drawn on the camera
you're using a screen space overlay canvas
it is drawn directly on the screen
with 1 unit (1 meter) = 1 pixel in the scene view
that's why it looks huge
so that means the camera is irelevant?
this is normal and fine
In regards to this canvas, the camera is irrelevant yes.
aaaaaaaaaaaaaaaa
that makes sense
I was thinking about having a large background and when going through the buttons the camera move as well
theres a Developmental Build
ok ill try that
sorry, where could I send
a, got it
going to delete it
I think calling one IEnumerator (yielded every 3 seconds for checks) is causing another one to stagger (yielded every 0.1 seconds for animating) is this possible?
Coroutines will not affect other coroutines generally unless one is yielding on another. What weirdness are you seeing?
what do you mean by "stagger" exactly
can someone help me figure out why this always returns false, even when a debug shows that player transform is not null and draw ray shows the ray piercing the player so it definitely reached the player?
The staggering coroutine controls a "blinking light" image by adding/substracting from the Lerp value on its shader, the stagger is that it stops for a bit every 3 seconds or so, thats why i think the other coroutine might be responsible.
how long is "a bit"? if you're just using a loop with WaitForSeconds(3) in it, you're ot going to achieve a perfect 3 second consistent timer with a coroutine
The animation stops for about half a second, pretty noticable
your raycast is using max distance of 1
you need to put detectionRadius in the max distance param, not multiply it by the direction
Assuming detection radius is larger than 1, that could be the problem
Maybe show some code
changed it to this, and detection radius always stays at 8, but stil lreturns false
unless i misunderstood smething
that is correct as per what I was mentioning
what object are you expecting the raycast to hit?
Can you show the inspector for that object?
Also have you actually checked if and what your cast is hitting?
if (hit.collider != null) {
Debug.Log($"We hit {hit.collider.name} which is on layer {LayerMask.LayerToName(hit.collider.gameObject.layer)}");
}
else {
Debug.Log("Raycast hit nothing");
}```
could the raycast be hitting the thing it is being emitted from?
yes
ah
so I recommend this
any ideas why this doesnt work in the web build?
what is failing specifically?
And yeah if you're e.g. starting this with Task.Run, that's an issue.
I am awaiting it
it just waits infinetly i think
its a bit hard to know whats going wrong because it works in the editor
and it also works in app build
just not in web build
im not sure
i just await this
so i doubt it
i dont explicitly start a new thread for it
but isnt async always like multi threaded
not necessarily, no
ye tbh i guess its not rly cuz i await in the same line as i call
Have you checked the javascript console for errors?
Usually I just use coroutines for webgl and if I need to await I'd just poll the token till it's done
let me take a look
i didnt htink about that
that sounds rly confusing
Unity also has the awaitable class too which is actually good for it
i have NO clue what this means
im not rly that good with web dev
are you trying to access resource on a different location / domain
well ye from my api
its azure
but its just an api call
you have to add it to the headers
yes
and what do i add?
I think you have to do it from azure actually, Its been a bit since I touched unity webgl / js
i have no idea what CORS even is
its an azure thing
but im using free student stuff
so i dont have full features
wait the error comes directly from Azure?
nah
Not sure if unity make it easy, but if the page is using CORS rules, you need to add rules too to allow your traffic to endpoints
CORS is this btw: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
i get this
may just mean you need to add these to the page hosting your content:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Ha
did you look at the link I sent
the headers are to be added server-side
if you're getting the error from a server you don't own, use a different server
azure has many services
but are you using a Web App ?
im trying to send requests to the api
or. Serverless functions
Yes. What is your backend?
is it python? is it C#? php maybe
aaand I'm out xD
Learn how CORS as a standard for allowing or rejecting cross-origin requests in an ASP.NET Core app.
just use * as origin
this is the ASP.NET Core equivalent: policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
but if you WebGL build is on a specific site, it's recommended you use that specific site as origin instead
no just http://localhost. But if you're not sure use AllowAnyOrigin()
ok
weird i still get the error
show code?
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "_all",
policy =>
{
policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
});
});```
you need to app.UseCors() after that of course
yes
im not sure maybe it hadnt updated yet
let me test again
OH DAMN IT WORKS NOW
TY
np
yeah recommended to read a bit about CORS from mozilla website to understand what it is
converse with ChatGPT or browse stackoverflow or reddit if you need clarifications
but know that CORS is super important on web APIs 😛
smh my school didnt tell us anything about it
it even touches security -- like when you don't want your app to be embedded on another random webpage
i'm new to unity where should i start to learn?
i LOVE 2d but none of unity learn's pathways were what i'm looking for
I don't even use unity I'm just here :3
If you don't want to look at any Unity learn tuts, then search for tutorials online, like YouTube, etc . . .
okie
if you're already good with coding and know how to debug/experiment properly, then you can use tutorials to find out what exists relevant to what you need. Try implementing a feature, google to see what other people use to solve such problem, find out new components exist, experiment with it. That's pretty much what I did. Lots of tutorials by themselves are really bad if you follow step by step
i am completely new
then realistically you should be using the unity learn site, or at least start with c# basics outside of unity to give yourself a headstart. Being confused with unity AND c# at the same time is not fun
i've done a little bit and managing unity isn't that much for me
it's just C# and basics
why does it not consider player as visible?? the player is more than close enough
bool IsPlayerVisible()
{
if (playerTransform == null) return false;
Vector2 directionToPlayer = (playerTransform.position - transform.position).normalized;
float distanceToPlayer = Vector2.Distance(transform.position, playerTransform.position);
RaycastHit2D hit = Physics2D.Raycast(transform.position, directionToPlayer, detectionRadius, ~LayerMask.GetMask("enemies"));
Debug.DrawRay(transform.position, directionToPlayer * detectionRadius, Color.red, 1);
return hit.collider != null && hit.collider.gameObject.layer == LayerMask.NameToLayer("player");
}
maybe playerTransform is null?
nope i checked
also, why not just check if (hit.collider.transform == playerTransform)?
that probably is better indeed
Can you send pic of the player's hierarchy (+ inspector)?
Also your enemy does have the "enemies" layer on them right?
you'd be better off doing Physics2D.OverlapBox(pTr.pos, Vector2.one * 5, 0, ~GetLayerMask("Enemies))
yes its not hitting itself
player layer is not visible here but I assume it's correct
anyway go ahead and try with this, just in case
then switch to OverlapBox anyway 😛
i dont want it to detect the player when they are not actually visible, like if a platform is clocking the view
which is why i use raycast
yes
yes but Physics2D ignores Z AND sortingOrder, so your raycast is XY only
oh XY only is correct, I see.
does not already ignore z? cuz its physics 2d and the vector is vector2, and i give ray cast the righ direciton to the player anyways
and you've checked that Debug.DrawRay(transform.position, directionToPlayer * detectionRadius, Color.red, 1); draws the correct line?
yes
try Debug.Log(hit.collider) then.. something is blocking the ray
still false despite raycats clearly seeing the player
^ something's blocking the ray for sure
ah u were right
omg
its the damn stick
it has an invisible hitbox, so when u pick it up and it becoems child of the player, u can actrive the hitbox
as an attack
yeah imo be more explicit with your conditions
i have no clue how to create a good system with tags and layers
like an effecient system
for example, you can make the raycast not ignore ALL enemies, but only the SPECIFIC enemy that casts it
with all the stuff going on
and then check if hit.collider.GetComponentInParent<Player>() != null
i think ineed a package that allows a gameOvject to have multiple tags
or something more optimized depending on your computational needs...
no no... simpler is better
i feel like that is simpler
you can traverse up the hierarchy and check for the player
for example i could have a tree decoraiton that is a hiding place
then i have ground tag
if you think a whole package to maintain will be simpler than 1-3 lines of code then sure 😛
i want enemies to see through each other
i dont know how ill make the raycast only hit hiding decoration and ground
i wanna avoid making new layers as much as possible
you don't have to only hit specific stuff. The stick is child of the player, right?
if (hit.collider == null) { return false; }
var tr = hit.collider.transform;
while (tr != null) {
if (tr == playerTransform) { return true; }
tr = tr.parent;
}
return false;
ah.
ye that makes it a lil tougher
maybe fix its collider 😛
the bigger collider should only be a trigger at best -- which isn't intercepted at raycasts by default afaik
it is a trigger.. its still bein intercepted :/
ah well there's an overload that uses ContactFilter2D
you can disable hitting triggers if you use that
but by default it should've been disabled.. not sure what's going on there
not to be difficult but, is... there someother way? i want to add bushes with trig colliders in the future to block out the visibility for enemies
i use an older unity version maybe thats why
you can use RaycastAll and iterate through the things manually
if there's a ground or decoration, halt, otherwise, continue until you find the player or end of list
that gets everything that the ray cast hits?
yes, piercing
so a list colliders
and if the index of the ground is lower than the index of the player, that means the ground came first, meaning then player should be invisible. and if bush index is lower than player, then player is inside the bush and player should also then be invisible
yes I think so
I'm trying to make it so that the camera is attached to the body model's head when kicking when normally it isn't directly connected but it always seems to just base the length off the previous animation. There has to be a better way to do this right?
Could you use an animation event here instead?
Or a state machine behavior
I'll look up what that is 
bool IsPlayerVisible()
{
if (playerTransform == null) return false;
Vector2 directionToPlayer = (playerTransform.position - transform.position).normalized;
float distanceToPlayer = Vector2.Distance(transform.position, playerTransform.position);
RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, directionToPlayer, distanceToPlayer);
Debug.DrawRay(transform.position, directionToPlayer * detectionRadius, Color.red, 1);
bool playerHit = false;
int? playerIndex = null;
List<int> obstacleIndex = new List<int>();
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].collider.gameObject.layer == LayerMask.NameToLayer("Player"))
{
playerIndex = i;
}
else if (hits[i].collider.gameObject.layer == LayerMask.NameToLayer("Ground") ||
hits[i].collider.CompareTag("hiding spot"))
{
obstacleIndex.Add(i);
}
}
if (playerIndex != null)
{
if (obstacleIndex.Count == 0)
{
return true;
}
for (int i = 0; i < hits.Length; i++)
{
if (hits[i].collider.gameObject.layer == LayerMask.NameToLayer("Ground")) return false;
if (hits[i].collider.CompareTag("hiding spot"))
{
return false;
}
if (hits[i].collider.gameObject.layer == LayerMask.NameToLayer("Player")) return true;
}
}
return false; // Otherwise, player is visible
}
this is what i made, obv some stuff can be written more effeciently such as no need for obsticleIndex list, i could simply have a bool value doesIncludeObsticle and settings it to true instead of the line obstacleIndex.Add(i); but i kept it this way because i might do a change later because rn, if u stand between the ground and a bunch and an array hits at the right angle that it catches both ground and bush it would count player as invisible even if the player is not
inside the bush
which, considering i have flying enmeis with code that tells them to avoid the ground making such an angle hard to come by, i still dont like that im not doing this correctly, its hard to find an elegant solution for this.
at first i thought to have two trigger colliders for the bush, one surrounding hte bush and one actually inside the bush, and only if yo uare touching the one inside, without touching the one outside, then do you count as inside but then just connecting everythign together would be very tricky and akward
any... suggestion to this? lol
unless maybe there is a way to see how much of a collider %-wise is inside another collider
well you can check how close to the center of the collider the player is and infer something from that
you can presume if they are very close or at the center then they are "full inside"
You could have a few empty GameObjects placed on the outer extremities of the enemy model, and while you're inside the trigger you can check with ClosestPoint if all of the empty objects are contained in the collider. If they are, you are fully inside the collider
you can tune this to be more or less accurate using more or fewer points as needed
Im new to game dev (started yesterday) how would i make a button in 2d which is pressed if the player stands on it?
If you're looking for a very high-level idea for how to start, you could try getting your player to enter a trigger collider (that is a collider2d with IsTrigger = true) and get that to do something. There are a lot of ways that this could be achieved depending on how much physics math you want to get into, but I think that this might be a good starting quest.
Congrats for taking an interest, and welcome to the tribe!
Thanks! i will try to do that!
If you're looking for some things to search for to start with, take a look at understanding what OnTriggerEnter2D() does.
Also, look in your project settings and make sure that you understand that the 2D physics matrix exists. It looks like a triangular grid of checkmarks. That will be important...
k. One other question i have is if i have an object that will be duplicated and used in many different areas which has some children objects, is there a way to adjust the children of one of them and adjust all of the others if that makes sense?
use prefabs
ok ill try that. thanks
that worked! thanks
I'm impressed that you put that together so quickly! Here's a slightly more advanced way to do that:
Recognize a collision with your switch, look inside the collision and if some force is above some activation threshold, trigger an effect.
Look up OnCollisionEnter2D().
why does it not detect an intersect despite me being fully submerged in the trigger collider??
Looks neat. First of all, do you ever get "here" to print?
nope
thats the issue i cant figure out
something about using bounds to check if they intersect is wrong
Is it possible that there's an issue with the setup before you call this method?
I wish that instead of #💻┃code-beginner, there was a chat for #code-stupid-shit-that-drives-us-nuts
nope, i 100% give it correct parameters, the correct colliders, trigger beings the player, target being what the player hides in
real
idk, its late, maybe thats why, but i cannot let this go
I think I would have to see the test setup. That looks pretty solid.
i mean there are a lot of things, anything in specifc i could provide?
I don't really know what you're doing to test this. CalculateOverlapPercentage is a static function. I think I would need to see some kind of Unity-driven code, or a case where you're instantiating two objects at fixed positions and then trying this method, etc.
You could try changing the parameters to accept Rect directly instead of Collider2D, then just write some tests.
well, i call it here: https://paste.ofcode.org/Zd25qCaYtS56JfRJSDdCfZ
If I were you, I would rewrite this to accept Rect instead of Collider2D and just write a test case.
That way, you have only math and don't necessarily need to worry about what is going on in some physicalized game world.
By a test, I mean:
Rect A = new Rect(x,y,width,height);
Rect B = new Rect(x,y,width,height);
CalculateOverlapPercentage(A, B);
It's all boxes anyway. You can control the values of A and B. Once it works, you can substitude the rects for colliders (and their bounds).
@scarlet skiff I just asked ChatGPT to make a more easily-tested version of your code:
public static class PhysicsCalculations
{
public static float CalculateOverlapPercentage(Rect trigger, Rect target)
{
Debug.Log($"Trigger Rect: Min({trigger.min}), Max({trigger.max})");
Debug.Log($"Target Rect: Min({target.min}), Max({target.max})");
if (!trigger.Overlaps(target)) return 0f; // No overlap
Debug.Log("here");
float xOverlap = Mathf.Max(0, Mathf.Min(trigger.max.x, target.max.x) - Mathf.Max(trigger.min.x, target.min.x));
float yOverlap = Mathf.Max(0, Mathf.Min(trigger.max.y, target.max.y) - Mathf.Max(trigger.min.y, target.min.y));
float overlapArea = xOverlap * yOverlap;
float triggerArea = trigger.width * trigger.height;
return (overlapArea / triggerArea) * 100f; // Percentage of overlap
}
}```
Try to make sure it works with Rects. If it does, then the problem is with how you set up your tests.
Create an Awake() method on a MonoBehaviour with constant Rects and feed them in. Make sure that works before testing against actual colliders. It will take some steps out of your search.
this is what ive made so far. the idea is a platformer where you can change your weight
Awesome! Would I be right to assume that you are new to Unity, but not to C#?
ive done a little terraria modding which is csharp but other than that not much.
but yes i started unity yesterday
Alright, well it seems like you're moving fast.
Did you research other game engines before choosing Unity?
i did and i though unity looked like it would suit my needs best
Between the big three (Unreal, Unity, Godot), I would say that Unity is the most flexible. It is a graveyard of abandoned features that exist half-finished, but is the easiest to mold to whatever it is that you want it to do so long as you are competent as a programmer and are willing to put up with learning its history a bit.
does anyone know how to fix this im doing a collaboration and my friend owns the organization, whenever i try to check in this pops up
Godot is less refined, but catching up quickly, but holds on to gating its development behind support for simplified custom scripting. Unreal is exactly one thing which you need to mold deliberately into something else if you aren't making a first person shooter.
unrelated but how would i add a glow outline to an object?
In short, I don't actually know who uses Unity Version Control over Git LFS. Sorry. 😦
its ok thanks though
I'm not sure where to ask either. Maybe ping some channels; I think this is a question where we could all benefit from knowing how to direct it.
Did you Google the error? I don't use uvc either but there seems to be some relevant results when I search it up.
Are you on linux?
thats what im doing rn
im not sure
UGH. What?
I dont think I've seen many people actually give answers to uvc errors here 😅 you should 100% use git
Likely through a shader, but google to find tutorials which do what you need. Either way this isnt really a coding question or solved through code
Sorry, you caught me by surprise with that question. Do you know what Microsoft Windows is? @spice locust
Linux, the operating system
yeah
i have that
Is that what is running on the computer that you're using right now?
i think i have linux
ok thanks
I feel like anyone that uses linux would know they use linux. Maybe just give a screenshot of your desktop
well in your taskbar on the bottom of your screen is there a logo that looks like a window made up of 4 squares
We can see from the bottom bar if theres like the windows search or whatever linux has
yeah
then youre using windows
It's going to be windows
ok
I'm gonna guess that you arent far along in your project. I would highly recommend just swapping to git
@spice locust Does your desktop look anything close to this:
This?
We've already established they're using windows
The future is now old man 😅
yeah
Okay. That's windows, and not Linux.
It is version control. If you're new to coding also, you might be in a rough time. I would highly suggest starting by learning c# outside of unity.
Then with git, experiment on it with text files, things you don't care about potentially messing up.
@spice locust Okay. So regarding "ci" on "/", I would leave the issue to someone who might have some idea what "/" means with respect to whatever mounted directory that is referring to.
something like this?
would it be easy to emit some particles when i interact with my interactable?
ok thanks im also doing the version control with a dev thats been deving for a year+
ok
It's one function call, so yes
k how qould i do that exactly
@spice locust It's genuinely hard to talk about these things if you aren't entirely sure about file systems. If it's a common error that you're seeing, those of us who don't know about Unity's built-in version control can't ask you questions without probably going a bit over your head, which wouldn't help anybody. Perhaps it is best that your friend figure it out for you because we can't really help if you don't know basics of version control.
Ok it might be hard to convince them to swap, especially if it's coming from someone who hasnt coded before.
Not to sound condescending, but understanding what operating systems are out there is level 0.
yeah
they are the owner of the orginization so hes the owner of the project
so he would have to give me permission i think
he tried too
but i looked on chatgpt and i think its gonna help
Honestly, let them figure it out or hire someone if he doesn't know. It's 1000% harder for us to guess at what your situation is.
From what I saw online, it does just seem like a permission issue.
ok thanks sm
Is there a question with this? If you're showing the warning, it's quite clear in what its saying
That you cannot new a monobehaviour
One of the great things about game development is that it encourages people to pick up technical skills, but nobody is psychic here. If you're behind or unfamiliar with what you're dealing with, we cannot place ourselves in your shoes and see things as you do.
Play the particle system wherever it is you handle your interaction
That's a good thing, though!
yeah!
First warning is important you should read it
Yeah. You've taken the moving parts out of the problem. Now you can try to solve the issue using rects that you could technically write down on paper. A good starting point would be that (rect, rect) should return 100 if it works.
Groannnnn
Get off my lawn.
@spice locust If you're looking for a source of truth, whoever is asking you to use version control should be able to explain to you what they expect. It shouldn't be your job if you're coming into a project to figure out how to help them help you as the first thing that you do.
I know this might be complicated but how do you print something to the console
I've forgotten.
Debug.Log
Thanks
If I instantiate a prefab will a raycast right after that be aware of it’s colliders? And if not can i call for a early physics update or do I need to wait for the collider to initialise
This question is basically asking about the execution order of Unity Events (Update, FixedUpdate, etc.)
it did return 100
Okay, are you familiar with unit tests?
uhh not really 😅
yes
FixedUpdate comes immediately after any physics calculations, but Update is desynchronized from that. Whether this will happen depends on exactly when you're instantiating something. If it's on FixedUpdate, it will be on the next frame. If it's Update.... it depends I guess.
I know but I don't know how collider initialization plays into that
Collider interactions trigger on the physics step, right before FixedUpdate. 100% everytime, all the time.
So I actually would really recommend that you learn that now, because this is actually exactly the kind of problem that you can systemically eliminate in your project.
yes it will there's a thing called Physics.SyncTransforms() that syncs ALL transforms on the physics engine. There's also a thing called Physics.autoSyncTransforms that automatically syncs each specific transform that changes. That is on by default.
hmm i see looks like ill have to look up a tut. since this doesnt seem like something i can solve soon though ill have to push it til tmr
anything else i should keep in mind when i get the chance to check it out?
geez Unity is trying so hard to push Unity 6 lol.. All docs links contain 6000.0 now
I'm in a pretty strange crash state with my current project, else I'd share my stuff with you. Actually, I can try.
Unity has built-in support for NUnit if you want to start reading on that. @scarlet skiff I'll ping you if I can find a moment to help if you'd like.
please keep in mind this is #💻┃code-beginner :p
would love to, but it seems like something a little extensive, so ill have to circle back to it tomorrow, its 4:17 am where i am, so my ability to think creativly is quite dampned this late
not trying to start a whole thing here but this is code-beginner and your feeding a stranger chatgpt code and recomending unit testing
so... on the bright side if my errors require advanced solutions then im no longer a beginner?
lols, welp we were just wrapping up
I don't know if your errors require advanced solutions
collision intersection is abit more than most beginner stuff posted here but not crazy crazy
hmm maybe not, it does seem like just simple values dont wanna act right
@scarlet skiff Here is one of my tests files: https://pastebin.com/eS3HNUNK I can't show you how this looks inside of Unity, but you might be able to get an idea what those methods are for. The Assert directives basically work like return bool statements if they do or don't achieve the thing that they set out to do.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
testing with rect showed it worked... but with bounds it dont
Out of curiosity what do you need the overlap percentage for?
@scarlet skiff Here is how this looks in the tests inspector. Basically, you make methods that should always return true and they act like canaries in a coal mine... if ever you do something that would cause these test methods to fail, you get a loud error before the problem gets lost in your spaghetti.
check how much of the player is inside a bush, if enough of the player is inside a bush only then is the player invisible, i cant get a correct reading on if the player is sible or not with just ray casts (cuz at first i was like, well, if the raycat hits bush first, then that means the player is inside and hidden) because what if it does hit bush first, but goes through it and catches player, it might read that as player is insibile while they are not
What I would do with your percentage overlap method is create tests where you work out the math that if two rects overlap each other half-way in the X and Y coordinates, you get 25% coverage. If one is on the positive X side of a cartesian 2D system and the other is on the negative X side, you get 0%, and if the same rect is passed in for A and B you get 100%. Make a test that returns true in all cases and leave that forever in your project so that it will cry foul if it ever fails.
If the bush object is centered correctly can't you just distance check?
Then, start passing it colliders when the math works...
and the reason i use a raycastall is cuz i need to know the order of what ray htis first and i need the ray to go through certain things that i cant avoid with just configuring layers
I don't see the need for overlap Obada
uhhh ngl im getting a lil confused
a little? You must be a genius lol
Imagine this:
public void TwoPlusTwoIsFour() {
return (2 + 2) == 4;
}
You can go down whatever route you prefer but personally this seems like something your unintentionally making more accurate than it needs to be. You don't necessarily need to correctly check if the enemy "sees" the player when they are hiding in a bush you just want a mechanic where if a player is hiding in a bush good enough the enemy doesn't "see" them. distance checking and/or a specific trigger collider on the bush seems way easier to manage
I'd understand exactly 0 of these words as a beginner, for sure
it wont just be bushes, its gonna be trees, secret passages maybe, other stuff, and they might be tall and thin, or short and wide, they would need their own distance for the distance check, and i thought i might as wwell do it with overlap, at least here i can know the exact % of how much the player is inside, but i geuss it wasnt that simple
Consider the method that I just wrote. This is what we call a "test". It's a method that does some finite thing and returns a result if some logic is true. Does that make sense?
Can you draw a pic showing a single case in which you think overlap percentage is needed?
you can use a raycast in addition then
yes
because what if it does hit bush first, but goes through it and catches player, it might read that as player is insibile while they are not
This isn't how raycasts work
well, a RaycastAll does, no?
then don't use that?
i need it becayse this
you can avoid that by just configuring layers
RaycastAll doesn't tell you the order though
You'd have to sort the hits by distance
But yeah really just use layermasks
if you store stuff in an array or list, the first hting it hits would be index 0, second thing index 1, etc
Okay, so that method should return true 100% of the time. It wouldn't make much sense if it didn't. Consider wrapping your CalculateOverlapPercentage() method inside a test method like this:
public bool ARectFitsInsideItself() {
Rect myRect = new Rect(20, 30, 50, 60);
return CalculateOverlapPercentage(myRect, myRect);
}
This should never return false if your CalculateOverlapPercentage method does what you expect it to do.
not for that function; regardless just use layermasks
What tests do is give you an expanded way to write these kinds of things, assess that they do actually pass, then you leave them in like little triggers in case you ever change something in your code that makes them fail.
@scarlet skiff this is what you need:
var hits = Physics2D.RaycastAll(...);
var playerDist = 0f;
var closestObstacleDist = float.MaxValue;
foreach (var hit in hits) {
if (IsObstacle(hit)) { closestObstacleDist = Mathf.Min(closestObstacleDist, hit.distance); }
else if (IsPlayer(hit)) { playerDist = hit.distance; }
}
return playerDist < closestObstacleDist;
guys i did consider a few other options, i cant go through my thinking process right now, but i thoguht this was the best course, but maybe it isnt, but im thinking i might as well solve this, its a learning experience anyways, maybe someday i actually would requite overlap specifically, and because of this sutaiotn, id know how
you probably don't even need that
I was also under the impression RaycastAll returns them ordered
I was the one that recommended use of RaycastAll
Not trying to shame any learning here, absolutely go down those rabbit holes if you are having fun but for what your asking for you don't need a majority of this and if you don't understand how basic layermask and raycast use works this more advanced knowledge on the subject isn't going to sit as well in your mind
Hi all if you have a small cube as a trigger ( acting like as a light switch), how do you check if the lights are on, then turn them off, if the lights are off, then turn them on. I have this but it's not working. I use 2022.3.50f1 ```public AudioClip theSwitchSFX;
public AudioSource myAudioSource;
public GameObject thePointLight;
public GameObject theSpotLight;
void OnTriggerEnter(Collider dd){
if( dd.CompareTag( "Hand")){
//if is active , set inactive-TURNOFFLIGHT
if(thePointLight.activeInHierarchy){
thePointLight.GetComponent<Light>().enabled = false;
theSpotLight.GetComponent<Light>().enabled = false;
}
//if is inactive, set active-TURNONLIGHT
if(!thePointLight.activeInHierarchy){
thePointLight.GetComponent<Light>().enabled = true;
theSpotLight.GetComponent<Light>().enabled = true;
}
//In Either case play the switch sound
myAudioSource.PlayOneShot(theSwitchSFX, 1.0f);
}
}
honestly i cant read code anymore right now its late and ive been doing it for too long, the logic i have to detect whatever needs to be detected works the way it needs to, it just relies on working overlap % calculator, which i dont havw rn
@sour fulcrum why does your name look familiar 
lethal stuff maybe?
i do know how layermask works and have at least a basic understanding of raycasts, again i did consider them, you guys have to keep in mind there are other aspects in the game that would provide insight on hwy i chose this system but i cant go into right now, the items on the floor, the ground, the enemies, im at least somewhat confident that this is the best way
nah layermasks will work
🫠
feel free to elaborate when you have time
I think thePointLight.GetComponent<Light>().enabled = !thePointLight.GetComponent<Light>().enabled; would work
you're just inverting the value
then you wouldn't need the if statements at all so your code could just look like
public AudioClip theSwitchSFX;
public AudioSource myAudioSource;
public GameObject thePointLight;
public GameObject theSpotLight;
void OnTriggerEnter(Collider dd){
thePointLight.GetComponent<Light>().enabled = !thePointLight.GetComponent<Light>().enabled;
//In Either case play the switch sound
myAudioSource.PlayOneShot(theSwitchSFX, 1.0f);
}
}
Thanks a lot!!!
Happy to help
Is there reason why My stuff did't work, it kind of made sense. i thought it did. Also you forgot about the spotlight. Do i just do the same thing you did for the Pointlight?
You're on your way to getting it. When you are working on a method and need to get it to spit out some result, and its exposed in a simple enough way that you ought to be able to test it in specific scenarios, that's a great time to build tests to make sure that once it works, it keeps working through the life of your project.
oh im dumb, all good
Yeah you can do the same thing for the spotlight. The reason yours didn't work is activeinhieearchy checks if the game object is enabled, not the light component itself. Then you toggled the light component to inactive, but the game object it's attached to is still active
So your if statements weren't checking if the light itself is enabled which is what you're toggling
If you wanted to make the code more generic so you could have an arbitray number of lights, you could do this
public AudioClip theSwitchSFX;
public AudioSource myAudioSource;
//Use a list so that you can assign as many lights as you want
//Referencing the light component directly means you don't have to do GameObject.GetComponent<Light>() which is expensive to perform
public List<Light> Lights;
void OnTriggerEnter(Collider dd){
//Iterate through each light in the list and toggle if it's enabled
foreach(var light in Lights)
{
light.enabled = !light.enabled;
}
//play the switch sound
myAudioSource.PlayOneShot(theSwitchSFX, 1.0f);
}
}
```'
Out of curiosity for more experienced and/or professional Unity devs, Have you found any valuable use of Unity's Physics Material system?
Wanted to kinda hijack it for referencing data but it kinda locks me out of using it the intended way so curious what i'd be actually missing out on
what's the reason you want to do that
What's the best way to learn C# so I can learn how to learn to prevent myself from tutorial hell and other things.
I solve my own errors and stuff
It would be nice for me to associate a misc, arbitrary collection of colliders with a shared piece of referenced based data
(i would use tags but i refuse to use tags)
I'm unsure if I read your comment correctly, but this doesn't toggle if it's enabled; it flips the enabled state to the opposite value . . .
You do need to at least know C# and unity basics, so you'll need to go through tutorials/manual/unity learn for that. After that it's a free ride. Learn as you go. Look up tutorials for you specific thing, make sure to understand them instead of copying mindlessly. At some point you'll learn to come up with solutions yourself.
Thank you sir
The best advice is probably: have curiosity. Don't just accept things as is, but research how and why they work instead.
Well that's good cuz I'm a very curious man
I truly appreciate your advice
Thank you
Is there a difference between those two things?
Physics materials are used to determine how rigidbodies interact with each other
why not just make a class with that info
I know thats why they exist but i don't care about that
because then i have to add that component to every object with a collider which is abit ehhh
and then also require a getcomponent to try and find it vs. the collider having the reference built in
you know what static classes are?
Yeah
why not that
How would a static class be used in this context
you want the same piece of info accessible across every object no?
Sorry, I'm bad at figuring out what context I need to provide in my initial questions,
I want to check if a given collider has a given piece of referential data
also known as I want tags but i can't use tags so the next best thing
I'll pull up the code in a few but I just make my own tag class
so you can have multiple
gimme like 10 minutes and I'll pull it up I'm in a deadlock match
Nah it's all good
Not really interested in that option right now because it adds a getcomponent into the mix and requires active use of that new component which is a lot less attractive then potentially hijacking the physics collider reference
Would you not still need to use getcomponent on the collider and then access the physics material attached?
In these cases I already have the collider because of various physics events or raycasts
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
I don't use getcomponent. OnEnable and OnDisable adds/removes them from a static class and you can get a list of components with X tag
just call ObjectTagManager.FindAllObjectsWithTag(Tag)
I appreciate the suggestion but I'm alright on that for now
unless your game uses 0 physics I'm pretty sure you're gonna regret using the physics material to store non physics material data
I asked the initial question to find out more about those potential regrets 😛
The regrets are pretty simple. Your physics objects are gonna have random friction and random bounciness
and it makes your code 100x harder to read cause you have to go "ok this code is accessing my collider's bounciness but that's actually referring to the hp of the player with that collider" or whatever
When you say random are you actually refering to some sort of involved randomness?
I'm referring to the fact that changing the friction and bounciness of your physics objects for reasons unrelated to wanting them to have a different friction or bounciness is effectively random
your objects are going to arbitrarily change how rough/bouncy they are
What data are you trying to store with those values?
Mentioned it previously but i have no interest in actually using these physics colliders as intended
i don't want them to manipulate the physics at all
but what are you using them for
the material itself
Actually I'm pretty sure that changing the physics material asset doesn't update the physics material on every object with that. I think you'd have to reassign the material. Lemme check real quick
thats not what im interested in doing
What exactly do you want to achieve ?
It would help if you said WHAT you are trying to do
the point is that it has a reference to a physicsmaterial asset
i have said what im trying to do
no you haven't
I want to check if a given collider has a given piece of referential data
also known as I want tags but i can't use tags so the next best thing
you said you want to change the values in the physics material for reasons unrelated to the physics mateiral
but why
I never said i wanted to change the values in the physics material
i explicitly said i didn't want to
so you just want the name of the physics material?
I want the reference to the physics material object
The next best thing is a component that holds the referential data
what are you doing with the reference to the physics material object
as mentioned previously in the convo i'm not interested in that for the time being, heard though
using it to identify if that collider is relevant to me
Or a completely empty component I call a TagComponent
Would a layermask not work better for that?
the amount of unique usecases here makes that non viable and layermasks are also not viable for any potential modding support
The next best thing to a tag would be a component
It sounds like you've already made up your mind before asking tbh
no respectfully i was just asking for potential issues with my hypothetical solution rather than alternatives
i appreciate the help but your kinda stackoverflowing me here 😅
you do you dude
(this was my initial question for reference)
Yes, setting the friction and bounciness of a collider
I think you're trying to overengineer your code here. If you want to do that nobody's gonna rip your keyboard out of your hands
skimming through the conversation, i also don't see what you want here. the answer to your first question is obviously gonna be yes. It exists for a reason, it's value is if it solves your problem directly.
hijack it for referencing data but it kinda locks me out of using it the intended way so curious what i'd be actually missing out on
Then simply dont use it that way if you're aware already that this is a poor solution. Literally nothing is stopping you from making your own component that has a reference to the data you actually want and the rigidbody.
That is generally a horrible idea. How do you plan to encode the data via the physics material? A dictionary? Managing that and making sure materials do not change the way physics behaves would be a nightmare.
this doesn't seem to be a case of if the physics material is useful, it just seems like you're looking for justification to code something poorly. obviously no one is gonna encourage you to do it but it's your code at the end of the day
Also the fact if your object has a collider and a rigidbody, changing the physics material of one doesn't change the others
using UnityEngine;
public class ComparePhysicsMaterial : MonoBehaviour
{
public PhysicsMaterial2D material1;
public PhysicsMaterial2D material2;
private void Start()
{
var col = GetComponent<Collider2D>();
Debug.Log("Initial material: " + col.sharedMaterial.name);
col.sharedMaterial = material1;
Debug.Log("Material 1: " + col.sharedMaterial.name);
GetComponent<Rigidbody2D>().sharedMaterial = material2;
Debug.Log("Material 2: " + col.sharedMaterial.name);
}
}
you're just asking for errors
I have expressed no desired interest in this
/paste
You have expressed nothing about what you're trying to do other than you want to do something in a way that you know is wrong
The how do you plan to hijack the phys mat for storing data ?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
I know that it's an unintended solution but the official intended solution (the tag feature) is unsuitable for what I'm looking for so I was curious what my potential options we're. I know a class based system is likely objectively preferable but as I've previously had no usage of physics materials and I was curious if it was a viable option for me considering it's a built in piece of referential data. I asked the question to know if it was an actually poor solution in practice as due to my lack of using the system I am ignorant of all it's potential usecases
the physics material itself is the data i am storing
everyone has told you it is a poor solution and then you respond "idc I'm doing it anyways"
https://scriptbin.xyz/jaxovupoxa.cs anyone know why it shakes screen when im not shooting? also aiming no longer works and its because of recoil
Use Scriptbin to share your code with others quickly and easily.
official intended solution (the tag feature) is unsuitable
idk where you got the idea tag is the official solution. there are tags, layers, and the only thing i wrote as a solution was writing your own component which i believe to be the best from what i gathered. I didnt gather much though other than that you plan to reference this data, which doesnt really mean anything
Is there a certain part of this code related to screen shake? I'm skimming through it but not seeing it
recoil
ty
But what part? The name? The guid ?
I've had three reasons for why it's a poor solution which was
-that it modifies the physics of the object (if i cannot use values that reflect the state it would be in without a material this is a legitimate problem)
-that changing materials doesn't do something in a certain way? (I never expected it too)
-that it's a nightmare to manage (untrue without delving deeper into how its used)
I do not wish to come off combative here and I would appreciate if your comments did not give off those vibes either.
the object
there is a lot of code to go through here, you should really narrow it down. "aiming not working" could mean a lot of things
also add more debugs if something is happening when it shouldnt. that'll give you a clue at least of when its happening and why
Layers aren't viable because of their limited unique options
Tags aren't viable because they are a no-go for modding support
an additional component is my choice if there is a problem in my proposed physics material idea
the object, for comparison
i literally said it its because of recoil its located in update mostly and it calculates normal position i think
to revert back to that after i shoot and gun
Compare against what ? Unless you plan to have some sort of database linking the material object to some specific data ?
I would yes
What he's saying is your script is handling shooting, reloading, recoil, muzzle flash, and more it seems. It's hard to debug scripts that do so many things. I'm still trying to read through it but it's hard to keep in your head what would be going on in a script when it does this much
That is still a hell of a lot worse to maintain and modify than a simple component
Heck you can provide a base implementation and modders can code their own unique versions that do what they want
its mostly in update and issue is recoil ever since i added it it broke
yea i mean this is the part i was asking for you to narrow on "its located in update". just saying recoil the first time is incredibly vague considering the word appears a lot in the script
And still, add debugs so you can specifically see why stuff is happening. If there is code to shake the screen, and the screen shakes when it shouldnt, you should have debugs inside that method printing out every value. If a value doesn't align with your expectation, figure out why
You've got an extra opening bracket for one thing cs private void Update() { {
and yea u got a method in a method there
though it probably doesnt affect anything, HandleShooting() is in Update
What is your reason you're opposed to adding a component to store this data?
Biggest reason is that it adds a getcomponent call which if i can avoid why not
The reason im saying you need to debug it is because its borderline impossible to follow through someones code when theres a bunch of math and logic involved. Just having to figure out the flow alone makes me not wanna go through it (although other people may be more willing than me).
If you can narrow down like to an exact line/lines where the issue is, then its a lot easier to get help.
And general mangement of this component on what would otherwise be potentially uninteresting objects
Unless you would be doing that call 100s of times a frame the perf impact is negligible
@echo kite Are you modifying your camera's rotation in a different script
In the context of collision events and raycasts i could absolutely be doing that much yeah
they keep making getcomponent faster, funnily enough it's even faster in mono than il2cpp
player movement script handles camera movement but it worked fine before i added recoil
I'm pretty sure raycasting 100s of times a frame is more impactful than a getcomponent call. Plus you can cache the component after the first time accessing
We use components to identify different body parts and their dmg multiplyier and we fire hundreds of bullets per shot
The only thing I can guess from reading this is that the recoil has a reference to cameraOriginalRotation that's only set in Start, so if another script is modifying the rotation then it's trying to recoil based on an outdated rotation variable
again it's near impossible to debug code when it handles this many things at once
ok but i'm doing those raycasts for a reason so they are staying. Like a lot of things that use tags not all situations are cachable
when i click on a cooking stove, i want it to enter menu that it adds a semi transparent black screen where the cooking game is happening. i also want it so that whenever i left it, anything that happens here wont be reset.
im quite lost on this, anyone can give me hints on where i should look into? i was thinking about something with game objects being inside a canvas, but i had no clue on how to do that.
I'm just spitballing here so this might not be the best approach or even actually work, but maybe look into adding a canvas with a panel that's semi transparent over the camera, then using another canvas with a render texture and a second camera for the minigame
ahh second camera, great idea ty
Like I said we fire 100s of bullets per shot, we also get multiple components per bullet collision and the perf impact of this is negligible @sour fulcrum
I'm not saying to get rid of the raycasts. I'm saying that you're overengineering something that's almost certainly not going to be an issue. I gave you a suggestion with code that didn't involve getcomponent and could easily be cachable and work within whatever modding system you're trying to do
how do i revert back everything i did today i messed up stuff in inspector
Do you use Git? @echo kite
unity
Git is a separate thing
Git is a version control software. It lets you commit changes and then if you need you can go back to a previous version of your files
i didnt save it there
Do you know what git is?
github?
Github hosts git repositories. Related but not exactly the same thing. If you look up how to set up github desktop with unity, in the future you can avoid the headache you're having currently
gimme a minute I'll record a clip to show you why you want it
i dont need it rn i just wanna revert back so i keep my settings i had few minutes ago
start ctrl z'ing and hope it saved far enough 🤷♂️
you need version control (git) because it solves exactly what your problem is
it doesnt work
without git, you can very easily lose your entire project in a second. Months of work just 🪄 poof
you don't need it rn, you needed it an hour ago
then tough luck, you need git.
take this small mess up you had as an example. people have had corrupted projects before and lost a ton of work, you really dont wanna go through that
but what do i do now
remember what the values were and type them in
then install git and not have to do that ever again
it's 30 minutes of setup to save you hours of headaches or months of work lost
I could literally delete my whole project folder on accident, empty my recycle bin, and then use git to restore my project
Hell with github I could throw my computer into the ocean and then restore my project on a new pc
the only other thing you possibly could've checked, if that component was in a scene and you didnt save the scene. Otherwise the old values are overwritten
Just be careful with that you don't undo even more work than you intended if you haven't saved in a while
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
That links to unity's version control. I don't use that personally I use git, but it should do the same thing at the end of the day
Hello, i have some keys in my game and i want wen i pick it to destroy it, but when i pick one i can't pick other. The code is:
public void Interact(Player player)
{
player.AddKey(this.gameObject);
Destroy(this.gameObject);
}
You are destroying the key, what do you expect to happen?
But how i can only destroy 1 key?
You are destroying 1 key in the code you showed so I'm not sure what you are asking
i thought i had fixed this but im getting this again:
' from origin 'https://html-classic.itch.zone' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
my api literally has the thing to allow CORS
actualy let me ask this in the C# discord
ig its not rly unity
Ok, i find the error, you open my eyes, thank
@grand badger @wicked pulsar in case you guys are curios, i found the issue from yester... and honestly im embarrassed to even say it 🥲
js started vr development yall. wish me luck!
lets pray that google got all my answers for me...
good luck 🍀
from my experience in vr development unfortunately a lot of stuff is platform-dependent
not sure if unity has a centralised solution for all vr platforms to make cross platform vr development easier but vr is nonetheless fun to do
can someone help me out? im using the xr interaction toolkit but the "xr controller (action-based)" has been deprecated and i dont know what replaces it. chatgpt is giving me wrong answers and i cant figure it out. any vr dev able to help? never even coded before
update does not run in abstract classes even if a subclass of the abstract class exists on a live gameobject?
true or false
Log it ;p
You're overriding Update in a way that it doesn't call Enemy's update, only the inherited class.
In Enemy, make the function virtual
In inherited classes, call base.Update(); in the overridden Update functions
👍
Yo guys I’m making a first person shooter game, I made the camera rotate with the mouse but the player doesn’t move accordingly with the camera anyone knows the solution?
yup! So you're doing something like transform.position += transform.forward * Speed * Time.deltaTime;, right?
this inherits from currentPos += dir * magnitude;
so, to change the direction, you gotta adjust dir -- instead of transform.forward, using camera.transform.forward... kinda
float magnitude = Speed * Time.deltaTime;
Vector3 dir = camera.transform.forward;
dir.y = 0; // assuming you only move on XZ plane, not height
transform.position += dir.normalized * magnitude;
You would need to normalize that direction after setting z to 0
Also this doesn't account for horizontal
yeah tried to leave it vague with just a generic explanation 😛
in reality I'd go with var dir = Vector3.zero; and build up from there, adding vectors relative to the camera on dir, based on input
how do i make him unblur?
he is 32x32
also his name is james duckman
Is the imported image blurred at all or just the unity model?
@mortal ginkgo This is a code channel. Did you open the manual link I posted?
i did and learned nothing from it
Have you tried reading the Asset Settings section? Also don't cross-post, in unrelated channels as well.
nvm i got it
for reference to anyone interested: switch "Filter Mode" from "Bilinear" to "Point" (and consider enabling mipmaps)
It was answered already in the appropriate channel.
i did an oopsy
anyone wanna vc with me and walk me through making something?
you don't have to talk
If you have a question, ask it in the appropriate channel.
it is about coding
it's just hard to explain in text
i wanna screenshare and talk
Illustrate with a video then.
it'll have to be very very short for discord to accept
You can post up to 50 mb files here
and videos are big
If you need more than that then you are looking for a course or a tutorial. Which you can find in the pins.
ok fine then
i'll just ask how to make the thing i want and hope what i already have doesn't break it
i'm making a top down shooter but the player character is like vampire survivors so i don't want him to rotate, i want a cursor ro spin around him in a circle following the mouse
how would i make that?
You break it up into simple pieces and lookup how to do that.
I’m using rb.MovePodition
same rules apply -- code was more about direction calculation
Ok thanks
np
-_- what's the point of this channel then
To help people understand learning materials they have trouble with. Not do anything you request for you.
With rotation you start with this https://www.google.com/search?q=unity+look+at&oq=unity+look+at
Learn to use search engine and do manual examples.
Starting with !learn courses would teach you most of that stuff.
Right bot is dead. This https://learn.unity.com/pathway/junior-programmer
It's in the pins, like I've already mentioned.
that is in 3d
Unity is 3d. You clamp axis you don't need
Probably should start with https://learn.unity.com/pathway/unity-essentials instead. Will teach you engine specifics first.
Not rotating is easy, you get that for free. Just don't add in code that rotates it
https://paste.mod.gg/bocbbzuvqnpr/0 For some reason, my player refuses to decelerate and slide on ice. While I enter there, it just stops. Is something overriding my functions for it?
A tool for sharing your source code with the world!
Your code is just doing this:
Vector2 newVelocity = new Vector2(
inputHorizontal * speed,
rigidbody2D.velocity.y // Prevent upward launch
); // Prevent upward launch
rigidbody2D.velocity = newVelocity;```
so you're always setting your horizontal velocity directly to whatever your current input is * speed
so is there a way to make it decelerate? I'm kinda lost myself... I thought it would decelerate after leaving it.
seperate the inputs from the movingVelocity ?
don't set it directly immediately to 0
as you are now
use something like MoveTowards or Anim Curve to bring value back to whatever for a smoother transition
i started learning unity 2 days ago and i started by just making a new 2d project and look up how to do stuff as i go. Should i follow tutorials where i dont really understand everything thats happenieng yet and learn it later or should i make sure i actually know what everything does and why they use it?
Well, first off know your c#, but other than that I suggest mixing it up with Unity tutorials and tutorials on youtube to keep you interested
I've been looking for people with zero experience who might like a crash course in programming (C#) with Unity. If you're an adult, I'd be willing to do this via voice call. I did this for my friend last week, and it was a fun teaching experience for me, and a productive lesson for him.
Hi, im interested in learning code to make a game, where should i start? Can anyone recommend some youtube tutorials and guides please
Do you have any other programming experience?
!learn a few tips: don’t use ai to generate code, don’t use code from the internet unless you understand every line, id recommend doing unity learn first a bit to get the basics and dive right in, we’re here for when u get stuck
I have some basic knowledge of Java
Ok, ty 
Unity learn has a bunch of tutorials I was trying to link it with a bot but it won’t work
That’s good, unity uses c# which is quite similar to Java
This should be a little easier for you then
Ok, i will start doing this rn, thank you very much guys!
i have a question, since i have that if one of the players dies, both of the players respawns to the checkpoint, but is it a good thing or should i have them respawn sperately and not together?
Only you can answer that. It's your game design
Can someone tell me what I did wrong? for some reason my character wont jump at all, even after the game is unpaused. I'm able to move around, and i was able to jump until i changed GetKey(KeyCode.Space); to GetButtonDown("Jump");. https://pastebin.com/8S4Mfwbk
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
How do I fix these errors, there were two of the same scripts, and now these won't go away
Restart unity. If they're still there, you still have a duplicate
I did restart, but I don't see any duplicates
Ill try again
When I open up the Unity project, should I select, "Use Safe Mode"?
Doesn't matter unless the error is in an editor script
Search your project for classes named PlaceLandmine
Thank You! It's fixed
Look in your input manager and see which key the button "Jump" is associated with. It might not be the spacebar.
its still not jumping and this is my input manager
If you change it back to using KeyCode.Space, does it still work again? Maybe you changed something else?
how can i save and load a list of scriptableobjects whilst using json?
But the main reason i don't want to use it now is because of the fact that my jump isn't consistent, and i heard that GetButtonDown is more consistent with jump height.
GetButton and GetKey check every frame to see if the button/key is down. GetButtonDown and GetKeyDown only check once, and then not again until the key/button is released first.
It could be a problem with how "grounded" is being set. Try using GetButton("Jump") and I bet it will work.
not check but GetKeyDown returns true if the key was pressed down this update
vs GetKey which is "is this key held at all this frame"
Yes. Sorry, that's what I meant.
So jumping works with GetButton, but I want to solve the issue of my jumping being very inconsistent
I was about to advise you on that, actually. I think I know what's happening.
Try this: In your update, add:
if (!IsGrounded())
Debug.Log("not grounded");
When you hit play, you'll get a bunch of logs because your player starts in the air, but I think you'll continue to get more, even when they appear to be grounded.
Can you explain more, you could parse json and create scriptable objects in the editor or export scriptable objects to json in editor/runtime.
none of your videos work for me 🤔
Ok, I see. So it's not what I thought it was.
The last video showed that he doesn't get the Debug logs I suggested while grounded.
the boxcast has a very short distance of 0.5?
also not sure why GetComponent is done twice to get the size x AND y... You should avoid doing GetComponent a lot (do it in Awake/Start once) @ebon sapphire
if i have 3 identical objects with the tag "exampleTag", how would i reference all objects with that tag at the same time in code like if i want to modify the same variable in a script in each of them
A list/array of them?
how exactly would i do that though
[SerializeField]
List<MyThingy> myCoolList;
foreach(var thing in myCoolList)
{
thing.DoStuff();
}
k thanks
how should i change it?
lists and arrays are basic c# so you may wanna read up on that to make things easier
See what you did in Start for your Rigidbody? Do the same for your box collider. This keeps a reference to that component for future use, which is generally better than using GetComponent in Update.
so something like this?
Yup!
so what could be causing GetButtonDown to not work but GetButton to work? and how would i fix it?
if we wanna be pedantic you should get bounds once to a var.
my game has craftableItem scripting objects and a craftedItems list. so for example, if i craft a battery scriptableobject during runtime, it gets added into that crafteditems list during runtime as well. I was wondering how i could save this into a json file since jsons can't save scriptableobjects
You should seperate how you represent "game configuration data" and "runtime data to save". E.g. You have scriptable objects with data for how weapons work. You have another class that has an id of what weapon it is and some other extra custom data. Then you can save and load the runtime data without issue.
yes, i have something similar in my game which is a script called PlayerData which like you said is seperate from the game configuration data. in this class i have a string list of crafteditems id (which are just the name of the craftedItems) but im just unsure how to link this list to the actual craftedItems list and how i would get a craftedItem from a string from this list
well if you have a list in your player data of weapon ids for example, then you can have a Dictionary of your weapon data (where the key is the id) so you can easily retrieve the scriptable object. Pretty simple stuff.
e.g.
Dictionary<string, WeaponData> allWeaponData;
...
public WeaponData GetWeaponData(string id) => allWeaponData[id];
you would have a list or load all your weapon data assets and put them into the dictionary on game start so its ready for use
im sorry i dont think i understand what you mean by having a list of all the crafted item data assets and then putting them in a dictionary. are you saying that i should use the crafted item id list the load the scriptable objects into a dictionary by just using their itemId as a key and doing the same thing in reverse for saving the crafted items?
No i was giving an example on how you can retrieve the data easily with just a string id.
wasnt that the problem, how to load the data asset with an id?
yes, that was the problem
actually after further insight and practicing, your solution worked for me, thank you very much!
Could someone help me out with making my first survival game kinda like minecraft but not voxel? I just moved to unity from Scratch
Tutorials are in the pins
ah ok
You are going to need to learn how to code first
I could be like Dani and say hippity hooppity, someone code is now mine
legally
not illegal
Then its not your game now is it
it is called borrowing lol
fair
hello guys, i was wondering how can you store a data that been trained and generated by machine learning? i want to see if its possible to make the ai use that data instead of generating one again?
but what i recommend is learning how the code works so if you need to make tweaks to it you can
I would do that
You can steal code, everyone does it all the time on the internet…you just need to know what it means or else it’s useless since if something goes wrong you can’t fix it
(Steal code from like a stack overflow answer not an actual game)
anyone open to answer this?
Depends. What framework are we talking about?
Also, it's probably better asking in #1202574086115557446
its a general question i had, didnt build it yet
There's nothing impossible in general. It depends on your implementation (or the implementation of the framework you're using)
i see
because by using nueral network, it requires a data set to be trained on. after beign learned i wonder how can we extract the genrated data so other ais use it without generating one
im using python
the method with weigh-input-hidden-output
You can't extract the data(assuming we're talking about training data). After training you only have the weights. Or parameters. These you could save as the model parameters. The exact method would depend on the used framework, unless you're writing your own from scratch.
i see
thank you for the info
This is unrelated to unity at all btw. Unless you're using unity provides frameworks. At which point ask in #1202574086115557446 . If you're using a third party framework, better ask in their community. If you're writing your own, you'll need to research and learn a lot. Maybe look at the pytorch or a similar open source framework code and ask in their communities.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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/kc07n4c5 does anybody know how i could use scriptable objects to spawn more asteroids when the original one is destroyed im kind of confused on how to go about it i kinda have an idea on what to do
a powerful website for storing and sharing text and code snippets. completely free and open source.
You should have a prefab that you insert the SO data into and just instantiate that prefab over and over
would i have the prefab in the bullet script
// spawn 2 that are 50 percent of the original size
// once the second ones are hit spawn two more that are smaller from the original ones
// then they dont spawn anymore when destroyed so basically three stages```
So you want 3 different prefabs, 1 for the big astroid, 1 for the medium astroid, and 1 for the smaller astroids
So 3 different prefabs and 3 different SO instances
Well, actually you can use a single astroid instance and have the SOs have the identity of it, but according to what you're doing with the SO it seems like you should just make 3 prefabs
ohh ok thank you i will try that out
Basically when you Kill() the first astroid prefab, make it instantiate multiple medium astroids, ect
I'd have each additional prefab reference local to the astroid itself and not the bullet
and have the astroid itself instantiate the next ones
so i should work off of my asteroid script directly and not my bullet script?
You want some method on the astroid to call (when the bullet collides) so the astroid itself should clean itself up and instantiate the next instances
Oh you do have some singleton manager that cleans it up? Either way, use OnDestroy Unity method or your own Destroy method local to the astroid
ohh ok thank you i will try this out
i have a replay system that im making that current works by recording a "data point" class every frame and saving it on a list to which it can be played back.
it works, but with the down side that just one second of data takes up one kb, this is bad considering that this is only from storing the players postion and mouse positon, and as im also planning on adding more variables to a data point.
my question is if there is a way that i can shrink down the the size of a single data point class as much as possible?
Most games replay data by just storing input and simulating that
thats pretty much what i do, all of the data points are stored in a list and when its played back a "dummy" player is spawned and every data point is passed into it
I mean, a kb a second doesn't sound unreasonable and I assume you're not storing this data at all, right
i mean when this data is put on a list, where is it stored, RAM?
I don't know much about the subject so just ignorantly throwing an idea your way but one thing you can do potentially is ensure that if your storing position and rotation per frame you don't save it if it hasn't changed since last frame as you can just refer to the last unique entry
and yeah im going to be storing multiple instances of that data
yeah that does sound good
like if the player is not moving
but yeah like Mao suggested a lot of games do this by recording the inputs instead to re-create the same experience. But I think that depends on how reliant you are on certain physics things(?) and such
also this might be a strectch, but would it work if i used smaller data types like 16 bit?
If you're writing to a file it doesn't necessarily need to be loaded into mem and you can chunk the data up for what is to be loaded for you do manage to create some very large clips.
wdym chunk up the data
don't read all the data in at once and deload the previous points
what would i use to do to that
this is the code i use to record data
// loop that will run every frame, creating a new datapoint class and adding it to the queue list
public void Update()
{
if (isRecording)
{
// create a new datapoint class
DataPoint dataPoint = new DataPoint(
player.transform.position.x,
player.transform.position.y,
cam.ScreenToWorldPoint(Input.mousePosition)
);
// print the contents of datapoint
print(dataPoint.x + ", " + dataPoint.y + ", " + dataPoint.mousePos);
// add the datapoint to the list
data.Add(dataPoint);
}
}
}
public class DataPoint
{
// store the players x,y position
public float x;
public float y;
// store the players mouse position
public Vector2 mousePos;
// constructor
public DataPoint(float x, float y, Vector2 mousePos)
{
this.x = x;
this.y = y;
this.mousePos = mousePos;
}
}
You can write using Json or use the binary formatter class but honestly I wouldn't worry too much about this unless you do run into problems
ok yeah thanks i was just thinking that i will eventually take up more space as i will be store more things than just the player posion
Yeah, it's what I'm thinking off the top of my head, but there's probably other ways around it
probably binary writer/reader instead of formatter given the security issues of it
if it's temporary I wouldnt worry too much
what issues
just a better practice to not use binary formatter at all
https://learn.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide
alr thanks
do you need the replay to be entirely accurate? you could also choose to not record certain frames if you're storing the current position. from what you said above, 1kb in 1 second would be like 256 floats. you have 4 floats in a data point, so i assume you're recording roughly 60 frames per second. This could probably be cut in half with almost no visual difference
One issue i think, because you're not recording the time, this might end up not being accurate in its current state anyways
if your replay logic is the same as your recording logic then the replay wont be guaranteed to run in the same duration
yeah it is recording in the main loop, and the replay system also does it at the same speed
input simulation would probably save you a lot of data as even holding input/analog can be simply be flags for when those values change
private IEnumerator Replay()
{
while (currentIndex < data.Count)
{
dummyInstance.transform.position = new Vector2(data[currentIndex].x, data[currentIndex].y);
currentIndex++;
// Wait for next frame
yield return null;
}
}
like this
where does it do it the same speed? nothing about your code cares about when a position happened
you should test this yourself at like 60 fps then set the target frame rate to like 10
In networking though, there's a similar usecase for this stuff and even though you do simulate input of clients you do have points to resync the character completely
well the recorder runs in a update loops at 60fps, and the replayer uses a yield statement to wait for the next frame so in practice it should both run at the same speed
are you recording and replaying at the exact same time? this doesnt seem to be the case given the video above
I really think you should just try it, record when running at your normal frame rate then set the frame rate much lower when replaying
you cant guarantee the game will always run at 60 fps
a lag spike for the user will make this inaccurate
no, rn i have some buttons that i press to record,stop and replay
so would it seem better to use someting like a fixed update to record and replay?
hey guys, im currently experiencing an issue having prefabs or sprites show up for my ingameitems using a creatorkit if anyone is able to help me
When apply a child UI/canvas object it has rect transform and my parent object is a sprite with normal transform how can I correctly transform the piece to its correct position without it being stuck at 0,0 (or whatever coords I initially set the object to)
hm i dont know if there would be downsides to fixed update here, but i'd likely still do my own logic to run it how often I want. Then also record the time so you know which position it should actually be going to
honestly yeah i think i would be better if i cut the data in half by recording every other frame
@eternal needle do u know if there is a function in unity that can do that
like a slower update function
this is very vague, you should specify what issues you're having. look at the #854851968446365696 on what to include when asking
it doesnt have to be every other frame, this shouldnt specifically care about the frame count because thats still the same issue. Just store and check the time, have some threshold about how long it should be until you record the next position.
And as for the function to do it, you just make it using Update.
@eternal needle im currently doing a computer science project using unity and the creatorkit: beginner code, where you have to add customizable items with custom item effects. i followed all of the instructions using 2022.3 3D URP, ive created the custom items and their custom weapon effects, but in the inspector when i assign both a sprite and a prefab to represent the item in game, neither of them appear. Im not entirely sure if theres something inherently wrong in the code for the usable items using the creatorkit (i doubt it) but i have a screenshot here as well of the inspector with both prefab/sprites selected for the usable item.
even when i create an in game item, without adding the effect and script i make, where its barebones with a world object prefab it still wont allow me to place it in the scene
ive also attempted to create an empty object, for example a cube, in the scene and add the item effects to it, but it says its not monoscript
and changing it to monoscript goes against the steps in the tutorial and i get a million different errors in the console
im a bit confused what you mean
in the inspector when i assign both a sprite and a prefab to represent the item in game, neither of them appear
The object you shown looks like a scriptable object, so it's not something that goes in scene at all. If a game object is using this scriptable object, i assume it's going to be reading the sprite and assigning that to some UI
which object in specific isnt functioning as you expect?
the agility potion, the really big staff, and the world's coolest shirt which are the 3 blue box items, could i possibly send you a link to the exact spot in the instruction that had me create those items?
its saying that when i apply a World Object Prefab, the scriptable items i made, would appear in the world as that prefab, but when i select one absolutely nothing happens and i cant place it
scriptable objects dont go in a scene, you cant place it in a scene. there is likely some code to instantiate the WorldObjectPrefab on your scriptable object
yea you can send it but i also haven't gone through the tutorials ever. I can see if theres any glaring issues though
okay ill send it here https://learn.unity.com/tutorial/customize-your-game?uv=2022.3&projectId=5d48025dedbc2a0020e85be2#6542071cedbc2a50f555fa14
This tutorial is a reference guide for further customization of the Creator Kit: Beginner Code game. It provides guidance to help you use script templates to create: Usable items with Usage Effects (like the health potion in the final tutorial) Equipment items with Equipped Effects Weapons with Weapon Attack Effects
im currently on the customize your game portion, at "create a usable item"
i think you might just have a misconception at what this scriptable object is for then. are you still trying to place it into the scene?
because thats not what its for
i think i might, because the scriptable objects are meant to be used in the game. for example a few other students have it uploaded, and the three objects they needed to create are in their game. do i need to LINK these items to an existing prefab?
yes
some game object will need to reference your usable item at some point and use it as described in the guide.
World Object Prefab: The 3D GameObject that will be created to show the Usable Item in the game world when it is spawned. If this is left empty (null), the item Sprite will be used instead.
is my issue that im trying to use prefabs or sprites that already exist and are attached to items already?
a scriptableobject is referenced by a monobehaviour the same kinda way an ikea instruction manual is found in the box of your new chair
the scriptable object is just used to hold information, thats all. in this case, its holding what information to actually spawn. It holds a reference to a prefab, it holds a reference to a sprite. neither of these are spawned in your scene
Something else needs to take your data container (usable item) and actually do something with it
okay i think i get it, so i have to attach that information to a 3d object. i was under the impression that's what i was doing when i selected World Object Prefab - potion_prefab
i just assumed it would automatically create that item, using that 3d model
id assume the guide would have some code or section on how to actually use those usable items but yea didnt look through it all.
Hey so i have a problem with a code on unity,i'm trying to recreate a fnaf game on unity 2d universal with a bunch of png images of my friends but I cant get pass the New Game Button everytime i try the script of the button it doesent work,anyone could help ?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
a message to the world to not implement an inventory system to a 2 days game jam as a beginner
A tool for sharing your source code with the world!
someone plz
I'm trying to Recreate a fnaf game in a 2D universal Environnement,everything was going well until i needed to code the "New Game" button,the code itself is working but when i press the button in play mod it doesent do anything.The code is attached under the button named "LoadGame" and the scene itself is named "12AM".The code is normally supposed to switch scenes.As you can see on the screen there's the script and the "On Click ()".And there's the script.Please someone help me and if needed i could provide other screenshots🙏😔.The tutorial i'm following has a 2019 version of unity so the steps are sometimes different.
I suck at coding 😔
Log a message inside of your method
yea try debug logging the Load12AM to see if the button works first
What ?
Debug.Log("Message");
is usually used to send you a message to your debug terminal. it can be used to check if a function works or not, so try add it in Load12AM to see if the button does indeed runs the Load12AM function
by default, its the Console tab on bottom of your screen
that tab will give output from Debug.Log("Message"); from your script
go ahead and try it
If I have a flags enum value how can i iterate through the selected choices?
read my messages again, i told u whr
like this ?
id recommend asking chatgpt about simplest stuff if u r still confused as much
and yes, like that
now try to press the button
have u try to ask an AI to help u?
im not saying you should completely use it to write your codes, but when you asks such simple questions, it will explain to u in the suitable level you wanted
what was the error?
i fargot to save the visual studio file mb
when i clicked the button nothing happened again
nw m8 haha
okay good, now what do we know from that information
im trying tio get help abt that 😭
well, youve put the debug log inside the function, but the debug log didnt come out any kinds of message from the console did it?
any conclusion on that?
🥀
the function isnt being called (executed)