#💻┃code-beginner

1 messages · Page 620 of 1

wintry quarry
#

Sounds like you want the clockwise angle. In which case you just need to reverse the order of the parameters

tawny grove
#

isnt counter clockwise the normal way?

#

let me reverse it and check

#

i think its because

wintry quarry
#

what do you get when you reverse

#

Vector2.SignedAngle(Vector2.right, directionToGhost)

tawny grove
#

vector2.angle is on a 180* scale instead of a 360*

#

let me check

wintry quarry
#

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;```
tawny grove
wintry quarry
#

stops working how

#

like what happens

#

also what is the end goal of all this?

#

What are you doing with this angle value?

tawny grove
wintry quarry
#

Can you show the code, a screenshot of the scene, and what angle it's returning?

#

And what angle you expect it to return?

tawny grove
#

sure

wintry quarry
#

How does this have you circle the player?

tawny grove
#

im trying to grab the initial angle

wintry quarry
#

so wouldn't you be driving the angle from a variable here instead of calculating it from positions?

#

I see

tawny grove
#

the first image is getting the initial angle when the enemy enters range, the second is using it (and increasing it) to set position

wintry quarry
#

Are you intentionally doing =- there?

tawny grove
wintry quarry
#

that's the same as just =- x is just the same as = -x

#

there isn't really a thing of =-

tawny grove
#

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

steel smelt
#

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

wintry quarry
#

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;
  }
}
tawny grove
#

does it need to be converted into rad? isnt sin 45* persay like sqr2/2, just as sin(1/4)r?

wintry quarry
#

Sin accepts radians

#

(and cos)

#

so yeah if you want to feed degrees in you need to convert

tawny grove
#

oh

wintry quarry
#

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

ripe matrix
#

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.

wintry quarry
fleet venture
#
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?
tawny grove
wintry quarry
#

in this case "A counterclockwise rotation on the z axis by rotationAngle degrees"

tawny grove
#

i have not reached that in math class 😭 ill look into it. tysm

fleet venture
mental prawn
#

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

rich adder
#

also not a code q

mental prawn
wintry quarry
mental prawn
wintry quarry
#

(not a code question)

wintry quarry
#

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

mental prawn
#

so that means the camera is irelevant?

wintry quarry
#

this is normal and fine

wintry quarry
mental prawn
#

aaaaaaaaaaaaaaaa

#

that makes sense

#

I was thinking about having a large background and when going through the buttons the camera move as well

fleet venture
#

Is it possible to run a built app in debug mode?

#

probably not right?

rocky canyon
#

theres a Developmental Build

fleet venture
#

ok ill try that

rich adder
#

you realize this is a code channel?

#

check the pins

mental prawn
#

a, got it

#

going to delete it

hallow sun
#

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?

wintry quarry
#

what do you mean by "stagger" exactly

scarlet skiff
#

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?

full code: https://paste.ofcode.org/wYCpCkSAKmEGnsDSBzGp89

hallow sun
#

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.

wintry quarry
hallow sun
#

The animation stops for about half a second, pretty noticable

wintry quarry
#

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

wintry quarry
scarlet skiff
#

unless i misunderstood smething

wintry quarry
#

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?

scarlet skiff
#

target of the raycast

#

omg wait

wintry quarry
#

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");
}```
scarlet skiff
#

could the raycast be hitting the thing it is being emitted from?

wintry quarry
#

yes

scarlet skiff
#

ah

scarlet skiff
#

yea i had forgotten to assing the enemy to the enemies layer

#

so it hit itself

fleet venture
timber tide
#

Is this multi-threaded?

#

if so then it wont work

wintry quarry
#

And yeah if you're e.g. starting this with Task.Run, that's an issue.

fleet venture
#

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

fleet venture
#

i just await this

#

so i doubt it

#

i dont explicitly start a new thread for it

#

but isnt async always like multi threaded

timber tide
#

not necessarily, no

fleet venture
#

ye tbh i guess its not rly cuz i await in the same line as i call

wintry quarry
timber tide
#

Usually I just use coroutines for webgl and if I need to await I'd just poll the token till it's done

fleet venture
#

i didnt htink about that

timber tide
#

Unity also has the awaitable class too which is actually good for it

fleet venture
#

idk what that means

#

i hadnt thought about checking the javascript console

fleet venture
#

im not rly that good with web dev

rich adder
fleet venture
#

its azure

#

but its just an api call

rich adder
fleet venture
#

what do i add

#

you mean to the headers of the request?

rich adder
#

yes

fleet venture
#

and what do i add?

rich adder
#

I think you have to do it from azure actually, Its been a bit since I touched unity webgl / js

grand badger
#

just the standard CORS stuff on your backend

#

what is your backend?

fleet venture
#

its an azure thing

#

but im using free student stuff

fleet venture
#

so i dont have full features

grand badger
#

wait the error comes directly from Azure?

fleet venture
grand snow
# fleet venture uh oh

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

grand badger
fleet venture
#

i get this

grand snow
#

Ha

rich adder
fleet venture
#

not yet

#

it says to add the headers but idk how to add the

grand badger
#

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

fleet venture
#

i do own it

#

i Uploaded code to azure

rich adder
#

azure has many services

fleet venture
#

its an API

#

its a database with an api

rich adder
#

but are you using a Web App ?

fleet venture
#

im trying to send requests to the api

rich adder
#

or. Serverless functions

grand badger
#

is it python? is it C#? php maybe

fleet venture
#

app service

#

these 4 do it

grand badger
#

aaand I'm out xD

fleet venture
#

its C#

#

core

grand badger
rich adder
#

uhh weird. I cant react with "This"

#

but yeah the link ^

grand badger
#

just use * as origin

fleet venture
#

ah great

#

ill try it

grand badger
#

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

fleet venture
#

what if its localhost?

#

then i have to use star right?

#

cuz ip changes

grand badger
fleet venture
#

the api already filters on ip

#

so i think allowanyorigin would be fine

grand badger
#

ok

fleet venture
#

weird i still get the error

grand badger
fleet venture
#
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "_all",
        policy  =>
        {
            policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
        });
});```
grand badger
#

you need to app.UseCors() after that of course

fleet venture
#

app.UseCors("_all");

#

i have that

grand badger
#

yes

fleet venture
#

im not sure maybe it hadnt updated yet

#

let me test again

#

OH DAMN IT WORKS NOW

#

TY

grand badger
#

np

#

yeah recommended to read a bit about CORS from mozilla website to understand what it is

fleet venture
#

ye

grand badger
#

converse with ChatGPT or browse stackoverflow or reddit if you need clarifications

#

but know that CORS is super important on web APIs 😛

fleet venture
grand badger
#

it even touches security -- like when you don't want your app to be embedded on another random webpage

mortal ginkgo
#

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

bronze jewel
#

I don't even use unity I'm just here :3

cosmic dagger
mortal ginkgo
#

okie

eternal needle
# mortal ginkgo i'm new to unity where should i start to learn? i LOVE 2d but none of unity lear...

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

mortal ginkgo
#

i am completely new

eternal needle
#

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

mortal ginkgo
#

i've done a little bit and managing unity isn't that much for me
it's just C# and basics

scarlet skiff
#

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");
   }

Full code: https://paste.ofcode.org/LpXP7n3Dp6gVWKbWPVE2Sv

grand badger
scarlet skiff
grand badger
#

also, why not just check if (hit.collider.transform == playerTransform)?

scarlet skiff
scarlet skiff
grand badger
#

Can you send pic of the player's hierarchy (+ inspector)?

scarlet skiff
velvet holly
#

Also your enemy does have the "enemies" layer on them right?

grand badger
#

you'd be better off doing Physics2D.OverlapBox(pTr.pos, Vector2.one * 5, 0, ~GetLayerMask("Enemies))

scarlet skiff
grand badger
#

player layer is not visible here but I assume it's correct

grand badger
#

then switch to OverlapBox anyway 😛

scarlet skiff
#

which is why i use raycast

grand badger
#

yes but Physics2D ignores Z AND sortingOrder, so your raycast is XY only

#

oh XY only is correct, I see.

scarlet skiff
#

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

grand badger
#

and you've checked that Debug.DrawRay(transform.position, directionToPlayer * detectionRadius, Color.red, 1); draws the correct line?

scarlet skiff
#

yes

grand badger
#

try Debug.Log(hit.collider) then.. something is blocking the ray

scarlet skiff
#

still false despite raycats clearly seeing the player

grand badger
scarlet skiff
#

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

grand badger
#

yeah imo be more explicit with your conditions

scarlet skiff
#

i have no clue how to create a good system with tags and layers

#

like an effecient system

grand badger
#

for example, you can make the raycast not ignore ALL enemies, but only the SPECIFIC enemy that casts it

scarlet skiff
#

with all the stuff going on

grand badger
#

and then check if hit.collider.GetComponentInParent<Player>() != null

scarlet skiff
#

i think ineed a package that allows a gameOvject to have multiple tags

grand badger
#

or something more optimized depending on your computational needs...

#

no no... simpler is better

scarlet skiff
#

i feel like that is simpler

grand badger
#

you can traverse up the hierarchy and check for the player

scarlet skiff
#

for example i could have a tree decoraiton that is a hiding place

#

then i have ground tag

grand badger
#

if you think a whole package to maintain will be simpler than 1-3 lines of code then sure 😛

scarlet skiff
#

wait i dont need multiple tags for that

#

ugh im lost

scarlet skiff
#

i dont know how ill make the raycast only hit hiding decoration and ground

#

i wanna avoid making new layers as much as possible

grand badger
#

you don't have to only hit specific stuff. The stick is child of the player, right?

scarlet skiff
#

not when its a ground item, no

#

which was the case here

grand badger
#
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.

scarlet skiff
#

ye that makes it a lil tougher

grand badger
#

maybe fix its collider 😛

#

the bigger collider should only be a trigger at best -- which isn't intercepted at raycasts by default afaik

scarlet skiff
grand badger
#

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

scarlet skiff
#

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

scarlet skiff
grand badger
#

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

scarlet skiff
grand badger
#

yes, piercing

scarlet skiff
#

so a list colliders

scarlet skiff
#

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

grand badger
#

yes I think so

prime cobalt
#

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?

wintry quarry
#

Or a state machine behavior

prime cobalt
scarlet skiff
# grand badger yes I think so
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

grand snow
#

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"

wintry quarry
#

you can tune this to be more or less accurate using more or fewer points as needed

hardy ibex
#

Im new to game dev (started yesterday) how would i make a button in 2d which is pressed if the player stands on it?

wicked pulsar
# hardy ibex Im new to game dev (started yesterday) how would i make a button in 2d which is ...

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!

wicked pulsar
#

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...

hardy ibex
#

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?

hardy ibex
wicked pulsar
# hardy ibex 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().

scarlet skiff
wicked pulsar
scarlet skiff
#

nope

#

thats the issue i cant figure out

#

something about using bounds to check if they intersect is wrong

wicked pulsar
#

Is it possible that there's an issue with the setup before you call this method?

scarlet skiff
scarlet skiff
#

idk, its late, maybe thats why, but i cannot let this go

wicked pulsar
#

I think I would have to see the test setup. That looks pretty solid.

scarlet skiff
#

i mean there are a lot of things, anything in specifc i could provide?

wicked pulsar
#

You could try changing the parameters to accept Rect directly instead of Collider2D, then just write some tests.

scarlet skiff
wicked pulsar
#

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.

hardy ibex
wicked pulsar
hardy ibex
#

but yes i started unity yesterday

wicked pulsar
#

Did you research other game engines before choosing Unity?

hardy ibex
wicked pulsar
#

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.

spice locust
#

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

wicked pulsar
#

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.

hardy ibex
#

unrelated but how would i add a glow outline to an object?

wicked pulsar
wicked pulsar
# spice locust 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.

spice locust
#

ok thanks

#

im gonna try looking for people that know how

eternal needle
wicked pulsar
spice locust
wicked pulsar
eternal needle
#

I dont think I've seen many people actually give answers to uvc errors here 😅 you should 100% use git

spice locust
#

wdym by linux

#

sorry im kinda new to unity

eternal needle
wicked pulsar
#

Sorry, you caught me by surprise with that question. Do you know what Microsoft Windows is? @spice locust

eternal needle
wicked pulsar
#

Is that what is running on the computer that you're using right now?

spice locust
#

i think i have linux

eternal needle
hardy ibex
eternal needle
#

We can see from the bottom bar if theres like the windows search or whatever linux has

hardy ibex
spice locust
#

ok

eternal needle
#

I'm gonna guess that you arent far along in your project. I would highly recommend just swapping to git

spice locust
#

whats git?

#

im kinda new to unity

wicked pulsar
#

@spice locust Does your desktop look anything close to this:

spice locust
#

no

#

my bottom bar is different

#

but the top is similiar

wicked pulsar
west radish
eternal needle
spice locust
#

yeah

wicked pulsar
#

Okay. That's windows, and not Linux.

spice locust
#

oh ok

#

thx

eternal needle
# spice locust whats git?

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.

wicked pulsar
#

@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.

hardy ibex
#

would it be easy to emit some particles when i interact with my interactable?

spice locust
eternal needle
spice locust
#

ive never used version control

#

so yeah

hardy ibex
wicked pulsar
#

@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.

eternal needle
scarlet skiff
wicked pulsar
#

Not to sound condescending, but understanding what operating systems are out there is level 0.

spice locust
#

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

wicked pulsar
#

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.

eternal needle
#

From what I saw online, it does just seem like a permission issue.

spice locust
#

ok thanks sm

eternal needle
# scarlet skiff

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

wicked pulsar
# spice locust ok thanks sm

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.

spice locust
#

yeah ik

#

it was worth a shot though

polar acorn
wicked pulsar
spice locust
#

yeah!

polar acorn
wicked pulsar
# scarlet skiff something like this?

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.

wicked pulsar
#

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.

shy ruin
#

I know this might be complicated but how do you print something to the console thinksmart I've forgotten.

sour fulcrum
#

Debug.Log

shy ruin
#

Thanks

sour fulcrum
#

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

wicked pulsar
wicked pulsar
scarlet skiff
#

uhh not really 😅

wicked pulsar
sour fulcrum
#

I know but I don't know how collider initialization plays into that

wicked pulsar
wicked pulsar
# scarlet skiff uhh not really 😅

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.

grand badger
scarlet skiff
#

anything else i should keep in mind when i get the chance to check it out?

grand badger
#

geez Unity is trying so hard to push Unity 6 lol.. All docs links contain 6000.0 now

wicked pulsar
#

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.

grand badger
scarlet skiff
#

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

sour fulcrum
#

not trying to start a whole thing here but this is code-beginner and your feeding a stranger chatgpt code and recomending unit testing

scarlet skiff
#

so... on the bright side if my errors require advanced solutions then im no longer a beginner?

#

lols, welp we were just wrapping up

sour fulcrum
#

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

scarlet skiff
wicked pulsar
#

@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.

scarlet skiff
#

testing with rect showed it worked... but with bounds it dont

sour fulcrum
#

Out of curiosity what do you need the overlap percentage for?

wicked pulsar
#

@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.

scarlet skiff
# sour fulcrum Out of curiosity what do you need the overlap percentage for?

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

wicked pulsar
#

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.

sour fulcrum
#

If the bush object is centered correctly can't you just distance check?

wicked pulsar
#

Then, start passing it colliders when the math works...

scarlet skiff
#

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

grand badger
#

I don't see the need for overlap Obada

scarlet skiff
grand badger
#

a little? You must be a genius lol

wicked pulsar
sour fulcrum
#

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

grand badger
#

I'd understand exactly 0 of these words as a beginner, for sure

scarlet skiff
wicked pulsar
#

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?

grand badger
#

Can you draw a pic showing a single case in which you think overlap percentage is needed?

sour fulcrum
sour fulcrum
scarlet skiff
#

well, a RaycastAll does, no?

sour fulcrum
#

then don't use that?

sour fulcrum
#

you can avoid that by just configuring layers

wintry quarry
#

You'd have to sort the hits by distance

#

But yeah really just use layermasks

scarlet skiff
wicked pulsar
# scarlet skiff yes

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.

sour fulcrum
#

not for that function; regardless just use layermasks

wicked pulsar
#

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.

grand badger
#

@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;
scarlet skiff
#

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

sour fulcrum
grand badger
#

I was also under the impression RaycastAll returns them ordered

#

I was the one that recommended use of RaycastAll

sour fulcrum
humble abyss
#

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);
    }
}
scarlet skiff
grand badger
#

@sour fulcrum why does your name look familiar susEyes

sour fulcrum
#

lethal stuff maybe?

grand badger
#

no...

#

welp.. maybe my 5am brain is playing tricks on me

scarlet skiff
sour fulcrum
#

nah layermasks will work

scarlet skiff
#

🫠

sour fulcrum
#

feel free to elaborate when you have time

velvet holly
#

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);
        }
    }
velvet holly
humble abyss
# velvet holly 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?

wicked pulsar
sour fulcrum
#

oh im dumb, all good

velvet holly
#

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);
        }
    }
```'
sour fulcrum
#

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

velvet holly
#

what's the reason you want to do that

queen adder
#

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

sour fulcrum
cosmic dagger
teal viper
teal viper
queen adder
#

I truly appreciate your advice

#

Thank you

velvet holly
velvet holly
#

why not just make a class with that info

sour fulcrum
#

I know thats why they exist but i don't care about that

sour fulcrum
#

and then also require a getcomponent to try and find it vs. the collider having the reference built in

velvet holly
#

you know what static classes are?

sour fulcrum
#

Yeah

velvet holly
#

why not that

sour fulcrum
#

How would a static class be used in this context

velvet holly
#

you want the same piece of info accessible across every object no?

sour fulcrum
#

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

velvet holly
#

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

sour fulcrum
#

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

velvet holly
#

Would you not still need to use getcomponent on the collider and then access the physics material attached?

sour fulcrum
#

In these cases I already have the collider because of various physics events or raycasts

velvet holly
#

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)

sour fulcrum
#

I appreciate the suggestion but I'm alright on that for now

velvet holly
#

unless your game uses 0 physics I'm pretty sure you're gonna regret using the physics material to store non physics material data

sour fulcrum
#

I asked the initial question to find out more about those potential regrets 😛

velvet holly
#

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

sour fulcrum
#

When you say random are you actually refering to some sort of involved randomness?

velvet holly
#

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?

sour fulcrum
#

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

velvet holly
#

but what are you using them for

sour fulcrum
#

the material itself

velvet holly
#

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

sour fulcrum
#

thats not what im interested in doing

charred spoke
#

What exactly do you want to achieve ?

velvet holly
#

It would help if you said WHAT you are trying to do

sour fulcrum
#

the point is that it has a reference to a physicsmaterial asset

#

i have said what im trying to do

velvet holly
#

no you haven't

sour fulcrum
#

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

velvet holly
#

you said you want to change the values in the physics material for reasons unrelated to the physics mateiral

#

but why

sour fulcrum
#

I never said i wanted to change the values in the physics material

#

i explicitly said i didn't want to

velvet holly
#

so you just want the name of the physics material?

sour fulcrum
#

I want the reference to the physics material object

charred spoke
velvet holly
#

what are you doing with the reference to the physics material object

sour fulcrum
#

as mentioned previously in the convo i'm not interested in that for the time being, heard though

sour fulcrum
charred spoke
#

Or a completely empty component I call a TagComponent

velvet holly
#

Would a layermask not work better for that?

sour fulcrum
#

the amount of unique usecases here makes that non viable and layermasks are also not viable for any potential modding support

charred spoke
#

The next best thing to a tag would be a component

velvet holly
#

It sounds like you've already made up your mind before asking tbh

sour fulcrum
#

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 😅

velvet holly
#

you do you dude

sour fulcrum
velvet holly
#

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

eternal needle
# sour fulcrum (this was my initial question for reference)

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.

charred spoke
eternal needle
#

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

velvet holly
#

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

sour fulcrum
echo kite
#

/paste

velvet holly
#

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

charred spoke
echo kite
#

!code

eternal falconBOT
sour fulcrum
# eternal needle skimming through the conversation, i also don't see what you want here. the answ...

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

sour fulcrum
velvet holly
#

everyone has told you it is a poor solution and then you respond "idc I'm doing it anyways"

echo kite
eternal needle
velvet holly
velvet holly
#

ty

charred spoke
sour fulcrum
# velvet holly everyone has told you it is a poor solution and then you respond "idc I'm doing ...

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.

sour fulcrum
charred spoke
#

What about the object ?

#

If there is one or not ?

eternal needle
sour fulcrum
sour fulcrum
echo kite
#

to revert back to that after i shoot and gun

charred spoke
velvet holly
charred spoke
#

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

echo kite
eternal needle
# echo kite i literally said it its because of recoil its located in update mostly and it c...

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

velvet holly
#

You've got an extra opening bracket for one thing cs private void Update() { {

eternal needle
#

and yea u got a method in a method there

#

though it probably doesnt affect anything, HandleShooting() is in Update

velvet holly
sour fulcrum
#

Biggest reason is that it adds a getcomponent call which if i can avoid why not

eternal needle
# echo kite its mostly in update and issue is recoil ever since i added it it broke

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.

sour fulcrum
#

And general mangement of this component on what would otherwise be potentially uninteresting objects

charred spoke
velvet holly
#

@echo kite Are you modifying your camera's rotation in a different script

sour fulcrum
bright zodiac
#

they keep making getcomponent faster, funnily enough it's even faster in mono than il2cpp

echo kite
velvet holly
charred spoke
#

We use components to identify different body parts and their dmg multiplyier and we fire hundreds of bullets per shot

velvet holly
#

again it's near impossible to debug code when it handles this many things at once

sour fulcrum
jaunty bay
#

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.

velvet holly
jaunty bay
charred spoke
#

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

velvet holly
echo kite
#

how do i revert back everything i did today i messed up stuff in inspector

velvet holly
#

Do you use Git? @echo kite

echo kite
velvet holly
#

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

velvet holly
#

Do you know what git is?

echo kite
velvet holly
#

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

echo kite
eternal needle
#

you need version control (git) because it solves exactly what your problem is

eternal needle
#

without git, you can very easily lose your entire project in a second. Months of work just 🪄 poof

velvet holly
#

you don't need it rn, you needed it an hour ago

eternal needle
#

then tough luck, you need git.

velvet holly
#

This is what git can do

eternal needle
#

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

echo kite
#

but what do i do now

velvet holly
#

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

eternal needle
#

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

velvet holly
#

Just be careful with that you don't undo even more work than you intended if you haven't saved in a while

#

!vc

eternal falconBOT
#
Using version control in Unity

Unity Version Control

git Git

Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.

velvet holly
#

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

soft creek
#

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);
}

ripe shard
soft creek
#

But how i can only destroy 1 key?

verbal dome
#

You are destroying 1 key in the code you showed so I'm not sure what you are asking

soft creek
#

I pick for example the blue key, but when i want to pick up the green key i can't

verbal dome
#

Double click it

fleet venture
#

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

soft creek
scarlet skiff
#

@grand badger @wicked pulsar in case you guys are curios, i found the issue from yester... and honestly im embarrassed to even say it 🥲

undone dragon
#

js started vr development yall. wish me luck! Unity lets pray that google got all my answers for me...

eager spindle
#

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

undone dragon
#

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

scarlet skiff
#

update does not run in abstract classes even if a subclass of the abstract class exists on a live gameobject?

true or false

timber tide
#

Log it ;p

eager spindle
#

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

scarlet skiff
#

👍

sweet pendant
#

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?

grand badger
#

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;
wintry quarry
#

You would need to normalize that direction after setting z to 0

#

Also this doesn't account for horizontal

grand badger
#

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

mortal ginkgo
#

how do i make him unblur?
he is 32x32
also his name is james duckman

thorn holly
fickle plume
#

@mortal ginkgo This is a code channel. Did you open the manual link I posted?

mortal ginkgo
fickle plume
#

Have you tried reading the Asset Settings section? Also don't cross-post, in unrelated channels as well.

mortal ginkgo
#

nvm i got it

grand badger
fickle plume
mortal ginkgo
#

i did an oopsy
anyone wanna vc with me and walk me through making something?

#

you don't have to talk

fickle plume
mortal ginkgo
#

it is about coding

#

it's just hard to explain in text

#

i wanna screenshare and talk

fickle plume
#

Illustrate with a video then.

mortal ginkgo
#

it'll have to be very very short for discord to accept

fickle plume
#

You can post up to 50 mb files here

mortal ginkgo
#

and videos are big

fickle plume
#

If you need more than that then you are looking for a course or a tutorial. Which you can find in the pins.

steel smelt
mortal ginkgo
#

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?

fickle plume
#

You break it up into simple pieces and lookup how to do that.

grand badger
#

same rules apply -- code was more about direction calculation

sweet pendant
#

Ok thanks

grand badger
#

np

mortal ginkgo
fickle plume
#

Learn to use search engine and do manual examples.

#

Starting with !learn courses would teach you most of that stuff.

#

It's in the pins, like I've already mentioned.

fickle plume
#

Unity is 3d. You clamp axis you don't need

polar acorn
brittle isle
wintry quarry
#

so you're always setting your horizontal velocity directly to whatever your current input is * speed

brittle isle
#

so is there a way to make it decelerate? I'm kinda lost myself... I thought it would decelerate after leaving it.

rich adder
wintry quarry
#

as you are now

rich adder
#

use something like MoveTowards or Anim Curve to bring value back to whatever for a smoother transition

hardy ibex
#

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?

timber tide
#

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

willow hill
old pier
#

Hi, im interested in learning code to make a game, where should i start? Can anyone recommend some youtube tutorials and guides please

fresh silo
thorn holly
old pier
thorn holly
#

!learn

#

Is the bot broken?

thorn holly
#
Unity Learn

Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.

thorn holly
fresh silo
old pier
hushed hinge
#

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?

wintry quarry
ebon sapphire
#

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

fresh silo
#

How do I fix these errors, there were two of the same scripts, and now these won't go away

polar acorn
fresh silo
#

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"?

polar acorn
#

Search your project for classes named PlaceLandmine

fresh silo
#

Thank You! It's fixed

willow hill
ebon sapphire
#

its still not jumping and this is my input manager

willow hill
#

If you change it back to using KeyCode.Space, does it still work again? Maybe you changed something else?

ebon sapphire
#

it is GetKey

sterile radish
#

how can i save and load a list of scriptableobjects whilst using json?

ebon sapphire
# ebon sapphire it is GetKey

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.

willow hill
grand snow
#

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"

willow hill
ebon sapphire
willow hill
#

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.

grand snow
grand snow
#

none of your videos work for me 🤔

willow hill
willow hill
grand snow
#

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

hardy ibex
#

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

grand snow
#

A list/array of them?

hardy ibex
grand snow
#
[SerializeField]
List<MyThingy> myCoolList;
#
foreach(var thing in myCoolList)
{
  thing.DoStuff();
}
grand snow
willow hill
# ebon sapphire how should i change it?

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.

ebon sapphire
#

so something like this?

willow hill
ebon sapphire
#

so what could be causing GetButtonDown to not work but GetButton to work? and how would i fix it?

grand snow
#

if we wanna be pedantic you should get bounds once to a var.

sterile radish
grand snow
sterile radish
grand snow
#

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

sterile radish
grand snow
#

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?

sterile radish
#

yes, that was the problem

sterile radish
#

actually after further insight and practicing, your solution worked for me, thank you very much!

vale berry
#

Could someone help me out with making my first survival game kinda like minecraft but not voxel? I just moved to unity from Scratch

polar acorn
#

Tutorials are in the pins

vale berry
#

ah ok

polar acorn
#

You are going to need to learn how to code first

vale berry
#

legally

#

not illegal

quiet sandal
vale berry
quiet sandal
#

fair

short grove
#

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?

quiet sandal
#

but what i recommend is learning how the code works so if you need to make tweaks to it you can

thorn holly
#

(Steal code from like a stack overflow answer not an actual game)

teal viper
teal viper
short grove
teal viper
short grove
#

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

short grove
teal viper
teal viper
# short grove 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.

pure drift
#

!code

eternal falconBOT
pure drift
#

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

timber tide
#

You should have a prefab that you insert the SO data into and just instantiate that prefab over and over

pure drift
#

would i have the prefab in the bullet script

timber tide
#
            // 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

pure drift
#

ohh ok thank you i will try that out

timber tide
#

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

pure drift
timber tide
#

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

pure drift
cyan osprey
#

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?

timber tide
#

Most games replay data by just storing input and simulating that

cyan osprey
#

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

timber tide
#

I mean, a kb a second doesn't sound unreasonable and I assume you're not storing this data at all, right

cyan osprey
#

i mean when this data is put on a list, where is it stored, RAM?

sour fulcrum
cyan osprey
#

and yeah im going to be storing multiple instances of that data

cyan osprey
#

like if the player is not moving

sour fulcrum
#

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

cyan osprey
#

also this might be a strectch, but would it work if i used smaller data types like 16 bit?

timber tide
timber tide
#

don't read all the data in at once and deload the previous points

cyan osprey
#

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;
    }
}
timber tide
#

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

cyan osprey
#

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

timber tide
#

Yeah, it's what I'm thinking off the top of my head, but there's probably other ways around it

eternal needle
#

probably binary writer/reader instead of formatter given the security issues of it

timber tide
#

if it's temporary I wouldnt worry too much

cyan osprey
#

what issues

eternal needle
cyan osprey
#

alr thanks

eternal needle
#

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

cyan osprey
#

yeah it is recording in the main loop, and the replay system also does it at the same speed

timber tide
#

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

cyan osprey
#
 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

eternal needle
#

you should test this yourself at like 60 fps then set the target frame rate to like 10

timber tide
#

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

cyan osprey
eternal needle
#

you cant guarantee the game will always run at 60 fps

#

a lag spike for the user will make this inaccurate

cyan osprey
# cyan osprey

no, rn i have some buttons that i press to record,stop and replay

cyan osprey
tulip karma
#

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

woeful carbon
#

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)

eternal needle
cyan osprey
#

@eternal needle do u know if there is a function in unity that can do that

#

like a slower update function

eternal needle
eternal needle
cyan osprey
#

alr that makes sense

#

thanks btw

tulip karma
#

@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

eternal needle
#

which object in specific isnt functioning as you expect?

tulip karma
#

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

eternal needle
#

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

eternal needle
tulip karma
#
Unity Learn

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"

eternal needle
#

because thats not what its for

tulip karma
#

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?

eternal needle
tulip karma
#

is my issue that im trying to use prefabs or sprites that already exist and are attached to items already?

sour fulcrum
#

a scriptableobject is referenced by a monobehaviour the same kinda way an ikea instruction manual is found in the box of your new chair

eternal needle
#

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

tulip karma
#

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

eternal needle
#

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.

tulip karma
#

ill scan through everything again.

#

thank you for your help

candid plover
#

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 ?

eternal falconBOT
jaunty bay
#

a message to the world to not implement an inventory system to a 2 days game jam as a beginner

#

someone plz

candid plover
#

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 😔

timber tide
#

Log a message inside of your method

jaunty bay
candid plover
#

What ?

jaunty bay
# candid plover 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

candid plover
#

Where's the debug terminal ?

#

(also thanks for helping me)

jaunty bay
candid plover
#

ah yes

#

and what do i do with it ?

jaunty bay
#

go ahead and try it

sour fulcrum
#

If I have a flags enum value how can i iterate through the selected choices?

candid plover
#

where do i put the Debug.Log("Message"); ?

#

i know in my script but where ?

jaunty bay
candid plover
#

like this ?

jaunty bay
#

id recommend asking chatgpt about simplest stuff if u r still confused as much

#

and yes, like that

#

now try to press the button

candid plover
#

i get errors on unity

#

cant launch the game

jaunty bay
#

have u try to ask an AI to help u?

candid plover
#

yes

#

i asked chatgpt

jaunty bay
#

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?

candid plover
#

i fargot to save the visual studio file mb

#

when i clicked the button nothing happened again

jaunty bay
#

nw m8 haha

jaunty bay
candid plover
#

im trying tio get help abt that 😭

jaunty bay
#

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?

candid plover
jaunty bay