#💻┃code-beginner

1 messages · Page 42 of 1

warm raptor
#

No, but in my case how i'm i supposed to update constantly the position of each player because i have only one script that decript the coordinate of each player, because if i dont get the coordinate of each player how are they gona move, I dont really understand where u want to bring me with ur Idea of hire a personne every day.

rich adder
#

you have to save the value of the PP Volume slider

rich adder
eternal needle
#

This script just is constantly doing unnecessary Get and Finds

warm raptor
eternal needle
#

You shouldnt try to make your own solution unless you realllllly know what you're doing

rich adder
#

building it with websockets is like using a paintbrush to paint a building instead of those industrial size paint sprays

#

start with Netcode or something

#

I'm gonna take a wild guess that your rigidbody is too fast and you need to at least enable Continious collision checking on rigidbody

eternal needle
#

Just for start, using gameobject.find to look for the player isnt gonna give you what you expect always. Once you add a 2nd player, this breaks

rich adder
#

yeah you would not use a string of "Player" you would not be able to distinguish who . They're all technically "Player"

#

a copy of each other

acoustic arch
#

https://hatebin.com/ygzyeeyjhz
so i made progress on my inventory, but how do i set the itemInSlot to the item in the inventory in a way that it can eventually be moved around?

rich adder
#

this is not what was mentioned yesteday @acoustic arch

#

why are you storing gameobjects

#

thats the most useless type to store in unity

acoustic arch
#

oh

rich adder
#

any script on a gameobject has reference to that object / transform

warm raptor
# eternal needle Which part of your script is even multiplayer? Every multiplayer solution will h...

Ok so I explain how m'y multiplayer work:
So i have m'y FPS caracter that retrieve is coordinates and rotation After the script send the coordinates of the player to the serveur, the serveur give an Id to the new connected player. After the serveur send back the coordinates of all player except ur own message to the script the script decript the message and update the variable ID X Y Z if the Id is not in the list of connected player, the script created a new clone of ennemie player with a script were the ID of the ennemis is referenced.
And After for each message that the main script receive each clone look if the message has the same ID as what they have and if it's the case the clone get the coordinate and apply them to himself
So that basicly how it work
Again sry for my Bad english

acoustic arch
rich adder
acoustic arch
#

alr

#

i did that at first

rich adder
#

You still have 2 lists/arrays

acoustic arch
#

but then how do i change the actual slots sprite to show it?

rich adder
#

which gets it from the assets's SO

acoustic arch
rich adder
#

the SO should store things like name, stats, info, and icons /sprites

acoustic arch
#

yeah it does

rich adder
#

so then yeah you're literally overcomplicating it with having 2 lists to manage n all that

eternal needle
acoustic arch
rich adder
#

slot has all the info you ever need

#

Inventory deals with slots

#

it only means logical sense to have a List<Slot>

acoustic arch
#

ohhhh yeah cuase the slot already stores the item

#

mb

rich adder
#

exactamundo

acoustic arch
#

alright

rich adder
#

and Image should only be dealt from Slot

#

inventory should not care about Image components

#

it is the logic

#

eg adding / removing items to slot

acoustic arch
#

yeah

#

which is a lot simpler than what i was doing beforehand

#

my code no longer looks gross

rich adder
#

🙂 yea it helps when things are neatly encapsulated

alpine mortar
#

mate I cant figure this out

#

!code

eternal falconBOT
alpine mortar
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Rendering.PostProcessing;
public class Brightness : MonoBehaviour
{
    public Slider BrightnessSlider;

    public PostProcessProfile brightness;

    public PostProcessLayer layer;
    
    AutoExposure exposure;
    
    void Start()
    {
        brightness.TryGetSettings(out exposure);
        AdjustBrightness(BrightnessSlider.value);
    }
    public void AdjustBrightness(float value)
    {
        if (value != 0)
        {
            exposure.keyValue.value = value;
        }
        else
        {
            exposure.keyValue.value = .05f;
        }
    }
}
rich adder
#

no

#

dont change the profile or is that a custom script

eternal falconBOT
alpine mortar
rich adder
#

brightness.TryGetSettings(out exposure);

#

all this is unecessary

#

all you had to do was reference Volume

#

and tie it to slider

#

save the value in playerprefs, done

alpine mortar
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Rendering.PostProcessing;
public class Brightness : MonoBehaviour
{
    public Slider BrightnessSlider;

    public PostProcessProfile brightness;

    public PostProcessLayer layer;
    
    AutoExposure exposure;
    
    void Start()
    {
        AdjustBrightness(BrightnessSlider.value);
    }
    public void AdjustBrightness(float value)
    {
        if (value != 0)
        {
            exposure.keyValue.value = value;
        }
        else
        {
            exposure.keyValue.value = .05f;
        }
    }
}
#

like this?

rich adder
#

wat

#

how's that Volume component

alpine mortar
#

what is Volume

rich adder
#

so you couldnt ask for this earlier instead of just doing w/e you thought was correct 🤔

alpine mortar
rich adder
#

oh this is the old PPv2 stack..

#

Why didn't you say BrightNess is your Volume

alpine mortar
#

now you know

warm raptor
rich adder
#

anyway what exactly isn't working ? @alpine mortar

acoustic arch
#

https://hatebin.com/oyplzkpaoq
alright changed it so now it should be correct, but im not sure how i would add items into my inventory then? just find the first slot that doesnt have any item in it and put it in there i assume?

alpine mortar
rich adder
alpine mortar
#

and no, i dont know how to use playerprefs

rich adder
#

because I dont see the Black Color from Color Adjustment

alpine mortar
#

in other screens it doesnt

rich adder
rich adder
#

I've seen it in your script wdym you dont now how

alpine mortar
#

I don't know how

rich adder
#

PlayerPres.SetFloat("myslidervalue", slideravalue)

#

PlayerPrefs.Save

alpine mortar
#
void Start()
    {
        brightness.TryGetSettings(out exposure);
        AdjustBrightness(BrightnessSlider.value);
        PlayerPres.SetFloat("myslidervalue", slider value)
        PlayerPrefs.Save;
    }
rich adder
#

BrightnessSlider.value

#

also dont copy myslidervalue lol

#

its an example

#

name it something smarter

#

like BrightnessSliderValue

quick swift
#

hi! i think this is a simple fixable thing but ive been half an hour trying to fix it and cant seem to get to the answer, can someone help me?
basically when i press play the charater moves, everything good but the only thing that is not working is the direction the character is facing, its always facing left instead of forward and cant make it look the other way

the problem seems to be in the code, since even if i change the rotation of the model itself it starts facing left as soon as i move it, the code is the next one

using System.Collections.Generic;
using UnityEngine;

public class Playermovement : MonoBehaviour
{
    public CharacterController controller;
    public Transform cam;
    public float speed = 6f;
    public float turnSmoothTime = 0.1f;
    float turSmoothVelocity;

    // Start is called before the first frame update
    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");
        Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

        if(direction.magnitude >= 0.1f)
        {
            float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;

            float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turSmoothVelocity, turnSmoothTime);
            transform.rotation = Quaternion.Euler(0f, angle, 0f);

            Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
            controller.Move(moveDir.normalized * speed * Time.deltaTime);
        }
    }
}
#

and sorry for the walltext

alpine mortar
#

@rich adder I've done it but it says "error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement"

rich adder
alpine mortar
#
void Start()
    {
        brightness.TryGetSettings(out exposure);
        AdjustBrightness(BrightnessSlider.value);
        PlayerPrefs.SetFloat("BrightnessSliderValue", BrightnessSlider.value);
        PlayerPrefs.Save;
    }
#

Assets/Scripts/Brightness.cs(21,9)

#

re reference, the last bracket is line 22

wintry quarry
rich adder
#

ah wops

#

how i miss that

#

notice anything different

alpine mortar
#

I have to put "public static void Save();"

rich adder
#

uh no

#

its a method

#

and what do we do with methods

alpine mortar
#

put it at the start?

rich adder
#

lol

wintry quarry
#

note that every other line of code in your example is calling one

#

correctly

#

except that last one

quick swift
#

()?

rich adder
#

no cheating UnityChanOops

quick swift
alpine mortar
#

()

#

I didnt cheat

#

I fugured it out

alpine mortar
quick swift
#

np i was insecure of the answer tho lmao

rich adder
#

when in doubt look into C# docs

quick swift
#

thanks in advance ;w;

alpine mortar
#

!code

eternal falconBOT
alpine mortar
#
void Start()
    {
        brightness.TryGetSettings(out exposure);
        AdjustBrightness(BrightnessSlider.value);
        PlayerPrefs.SetFloat("BrightnessSliderValue", BrightnessSlider.value);
        PlayerPrefs.Save(AdjustBrightness);
    }
#

I think this is it

#

its not

rich adder
#

do you see anything in the () required

alpine mortar
#

no

#

ok

#

how many years have you been working with unity

rich adder
#

not long, I think 3 years

alpine mortar
#

doesnt work

rich adder
#

ofc it doesnt

alpine mortar
#

💀

rich adder
#

you're only saving it

#

you have to load it ?

alpine mortar
#

I ave to load it right?

rich adder
#

thats usually how saving works..

rich adder
#

luckily unity has one built in

#

lets make a thread tho, we're flooding the chat. should've done it sooner @alpine mortar

alpine mortar
#

Freddy thread

opal fossil
#

box or capsule collider for better detection if rigidbody is groundded?

rich adder
#

something like Physics cast

#

or overlap

opal fossil
#

the program thought my character wasnt grounded

wintry quarry
opal fossil
bitter carbon
#

Is it 2d or 3d

opal fossil
#

3d

bitter carbon
#

Ok

#

Idrk as i dont do it that way and am currently mostly using 2d

rich adder
wintry quarry
#

you probably should use a BoxCast instead of a Raycast if your collider is box shaped

opal fossil
dull eagle
#

Hey everyone, is there a way to change a prefab for a gameobject during runtime similar to have you can change the prefab in the inspector with the '+' button?

teal viper
slender nymph
#

just fyi modding discussions are not allowed here. you are better off asking for help with your anti cheat stuff in the modding community for SCP:SL

elfin eagle
#

I'm having this problem where when I load this scene my camera zooms out very far, I don't have this problem anywhere else when I load in a new scene so im not sure what is happening here

slender nymph
#

show any relevant code

elfin eagle
#
 if (collision.CompareTag("BlacksmithTeleporter") && Input.GetKey(KeyCode.E))
 {
     SceneManager.LoadScene(2);
     transform.position = new Vector2(1.994f, -1.569f);
 }
slender nymph
#

this code does not seem related to your camera's positioning

elfin eagle
#

oh my bad. im using cinemachine and it just follows the player

rich adder
#

Lens ortho size

#

where do you change that

slender nymph
#

why is the orthographic size so small?

rich adder
#

yeah thats hella zoomed out

slender nymph
#

smaller would be zoomed in, no?

rich adder
#

oh yeah ur right mb

slender nymph
#

which makes this even weirder. are their objects just incredibly tiny?

rich adder
#

super tiny lol

slender nymph
#

i bet they are using like 16x16 or 32x32 sprites and just left the PPU at 100

rich adder
#

@elfin eagle do you change the ortho size anywhere ? or maybe switch cam

elfin eagle
#

im using 16x16 sprites

rich adder
#

but what is PPU size

slender nymph
#

then change the pixels per unit size on the sprite importer to be 16 instead of 100

elfin eagle
#

ohh ok that worked thanks. for some reason it was changed

ashen ferry
#

is there clean way to change number into nearest one which would divide into whole numbers with chosen x, idk whats the word in english lol. 49 would be 48 since 16 * 3 is closest, 60 would be 64 now cause 16 * 4 is closer than 16 * 3 whats the name for that

slender nymph
#

the default is 100 pixels per unit. you want that to be set on your sprites to the number of pixels that should take up 1 unit of space. since your sprites are 16x16 you would probably want all 16 pixels to occupy a single unit of space so the PPU setting should be 16

queen adder
#

how bad is this for a monobehaviour constructor?

slender nymph
#

well considering unity won't be calling it, i'd say it's 100% pointless

frosty hound
#

Monobehaviours can't have a constructor

queen adder
#

yea just a getaway

slender nymph
#

or do you mean this is supposed to act like a ctor since it isn't actually one?

queen adder
#

to instantiate a new one and plug what you do like how you would with a ctor

slender nymph
#

i'd personally return the instance after doing all that, but there's nothing inherently bad about it

queen adder
#

ah yea returning it can be a good addition

austere monolith
#

how do u make variables for a 3d gmae

#

im new to c# and im trying to learn

#

but all of the Brackeys videos are like 5 yrs old

slender nymph
#

there are beginner c# courses pinned in this channel

slender nymph
austere monolith
#

lol

rich adder
summer stump
#

Ahter

rich adder
#

ahetr

#

🤣

summer stump
#

Brackeys is terrible and causes a LOT of bad habits in newer coders.

queen adder
#

it's hater for me, so you all are wrong

summer stump
#

Wrogn lol

rich adder
#

wait is it ?

#

huh some sync issue in discord

#

thats funny

queen adder
#

internet has always been messing with emoji spam ever since

#

anyways

#

best way to learn c# is from docs itself

rich adder
#

painnnn

queen adder
#

there's a LOOOT examples and detailed to core

#

yea, have to practice tolerance though

slender nymph
#

just reading the c# documentation isn't super useful if you don't know how the language works at a fundamental level though. but there are some basic c# courses on the microsoft site which are a good way to get started with learning

rich adder
#

yeah even some simple C# function microsoft goes way too overcomplicated with example

austere monolith
#

which channel is the tutorial on?

elfin eagle
#

bro i found out the main issue why my camera was bugging out was bc when a new scene is created there is a new camera and i forgot to delete it so it was screwing up my other camera 😭

rich adder
rich adder
#

was gonna suggest you check new cams if you followed up on it with a reply 🙂 at least its sorted tho

elfin eagle
#

no yeah i changed the orotographic view that fixed it

#

but like doing this is much more convienet

queen adder
#

neat, didnt knew we have c# tuts on pins

opal fossil
#

my game uses 3d models but completely ignores the z axis. should i use 2d components?

rich adder
#

no

opal fossil
#

aight

sour fulcrum
#

If I have

    private Palette tilePalette = new Palette(typeof(TilePalettePreset));

    public virtual Palette palette
    {
        get => tilePalette;
        set => tilePalette = value;
    }

Is there a c# declaration thing that stops me from referencing tilePalette from even this script but still lets palette get and set it?

unreal imp
#

guys i have a problem,im making that if my object is near an explosion is set on fire and after the particle is destroyed the object explodes,but now im doing that if you get the object already in fire near an explosion its explodes with no time

#

but now the problem is that the explosion cause that the objects are destroyed by one

#

ignoring the first script

#

i have a bad english,i will send the script

#

you all know it xd

heady nimbus
#

Weird collider interaction question.

If you instantiate an object with a trigger collider, but parent it off something with its own collider, would you expect the new objects collider to behave the same as the parent..?

unreal imp
#

Here are the parts that may have problems (if you ask me, I will send the complete script): if (col.CompareTag("Toilet") && !col.GetComponent<ToiletBehaviour>().isInFire) { Vector3 direction = col.transform.position - transform.position; float distance = direction.magnitude; float forceFactor = 1f - (distance / explosionRadius * 2); float appliedForce = explosionForce * forceFactor; col.GetComponent<Rigidbody>().AddForce(direction.normalized * appliedForce, ForceMode.Impulse); col.GetComponent<ToiletBehaviour>().setOnFire(); } if (col.CompareTag("Toilet") && col.GetComponent<ToiletBehaviour>().isInFire) { col.GetComponent<ToiletBehaviour>().hitsReceived = col.GetComponent<ToiletBehaviour>().maximalHitsToDestroy; }

#

the setOnFire method: public void setOnFire() { isInFire = true; if (isInFire) { fire = Instantiate(fireParticles, transform); //fire.transform.position = gameObject.transform.position; Destroy(fire, random2); } }

heady nimbus
#

Short version: Instantiating a melee weapon off the player, but the weapons collider is picking up the players knockback behavior instead of respecting that it's supposed to be a trigger collider

rich adder
#

IDestructable or something

#

where is anything thats supposed to delay anything?

unreal imp
unreal imp
rich adder
#

not really sure what is supposed to happening?

unreal imp
#

and obviously i added a delay of delete the fire with the setOnFire method

rich adder
#

what do you need to do

unreal imp
#

I am in the characteristic part that they catch fire when they receive an explosion then explodes and if they are already on fire they explode without cooldown

rich adder
#

col.CompareTag("Toilet") && !col.GetComponent<ToiletBehaviour>().isInFire()

if you already check ToiletBehaviour its probably not even necessary to use tag as well

#
if(col.TryGetComponent(out ToiletBehaviour toilet))
{
    if(toilet.isInFire){
        //stuff if in fire
}else {
//stuff if not in fire
}
vale mountain
#

im making a multiplayer shooter with FishNet, this Rpc isnt doing anything?

#
    public void SetUserText(GameObject player)
    {
        UserText(player);
    }

    [ObserversRpc]
    public void UserText(GameObject player)
    {
        player.GetComponent<PlayerController>().userText.GetComponent<TextMeshProUGUI>().text = player.GetComponent<PlayerController>().user;
    }```
#

it's supposed to set 'userText' to have a value

#

for all players to see

vale mountain
#

ty

raw hamlet
#
if (direction < 0)
{
    direction = 360 + direction;
}

I have this code to make sure the angles always stay positive
however, when playing the game, the inspector shows negative values
does unity auto convert angles?
like it the angle is 315, does it make it -45?

polar acorn
#

There are literally infinitely many

north kiln
#

Angles read in code may differ from those displayed in the Inspector, this is because they are derived from the internal representation, which is a Quaternion.

polar acorn
#

Don't ever depend on the inspector rotation being a specific value. Keep track of your own angles and then set the eulerAngles yourself. Don't read from it and expect a single value to behave

north kiln
#

the inspector often displays user-authored rotations which have not undergone any transformation. You can set rotations beyond 180°, as what you see here is for authoring convenience. However, Quaternions don't over-rotate, and their representation is completely different though they both represent the same orientation.
Because the inspector can also show authored values you can easily confuse yourself believing that's what's actually happening at runtime; but in reality they're just an editor-only tool

torpid herald
#

In Visual Studio there's solutions and projects. I know I'll need multiple projects for each game so should I be making a solution for the entire game and putting all the projects in there, or does it not matter?

teal viper
late burrow
#

when i access dictionary["something"] does it both create new entry if this doesnt exist and overwrites existing one?

cosmic dagger
late burrow
#

yes but when writing

#

it works both when not exist and exist?

cosmic dagger
#

you can't create/add a new entry unless you write to it . . .

late burrow
#

yes write

teal viper
#

Accessing a non existing key would throw an error

late burrow
#

strange i tested and it not errors

teal viper
#

Regardless of whether you're reading or writing.

late burrow
#

dictionary["thing"] = "abc"

teal viper
#

Ah, nvm. Get and set are different.

#

With set it would work apparently.

cosmic dagger
# late burrow yes write

when using dict[key], this will overwrite the existing value or create a new value with the key . . .

late burrow
#

cool it will make code much cleaner

cosmic dagger
#

if using dict.Add and you pass a duplicate key, you'll receive an error. there's a difference between the two, so make sure you use them correctly . . .

late burrow
#

yes i notice add errors

#

so setting better

cosmic dagger
#

if you're not supposed to add/have a duplicate key, then using Add is safer as that will produce an error. using the Set method will overwrite the value . . .

#

only use Set if you can (allow) overwrite the value of a duplicate key . . .

wicked cairn
#

How do I add reference? (mysql)

north kiln
#

You can't modify that via an IDE. You are using the default assembly, which automatically references every valid plugin in the project

#

If you used assembly definitions you could control that manually in Unity

wicked cairn
#

Darn. Well, How can I add the mysql references?

#

I download the dll

north kiln
#

And is the DLL in a Plugins folder and functioning properly?

wicked cairn
#

oh. I create a plugins folder in Assets and add the dll?

#

ok added

#

In the script theres no errors but in the console it has this

north kiln
#

You have to include every assembly it requires until all the dependencies are satisfied

wicked cairn
rich adder
#

why not just use sqllite ?

#

works very well in unity and its like 1 or 2 dlls

wicked cairn
rich adder
#

huh you're putting a remote db with dll ?

wicked cairn
#

ive written the php and can read data from the sql table but unity wont let me write the data without the imports

rich adder
#

I'm not familiar with php, can't you do like in JS where you can use express to make Api endpoints to interact with db?

#

that would only require unitywebrequest

wintry quarry
#

In fact your client app should absolutely not speak directly to the database

#

Certainly not write to it

#

If your Unity app can write to the database that implies you are shipping your database credentials with your app which is 😱😱

wicked cairn
#

admin panel

#

its only a build for me

teal viper
#

To write to a database, you need a key or something similar to be included in your app. But that means, that anyone can retrieve that key and write to your database whatever they want.

wicked cairn
#

I said its on a php file

teal viper
#

Then you don't need to access the db from unity as Praetor pointed out.

#

You just make a web request to your server to write or read data. The server handles accessing the db.

#

PHP implies you have a server somewhere.

#

Unless you're talking about something else.

wicked cairn
#

I do

#

I was trying to use sockets at first but it doesnt seem to work with unity.

#

and ig its not safe if it includes a ip

teal viper
#

IP is not a problem if you have a proper network setup server side.

#

Still not quite clear what you mean when you say that you have a PHP, but no server.

teal viper
#

You do have a server?

wicked cairn
#

I do

teal viper
#

I though the "I do" was answering the "unless you mean something else".😅

teal viper
wicked cairn
#

Was trying to write that to send the command to db. didnt work tho lol

#

But I guess last case, in the public build do web request 😞

teal viper
#

Shouldn't be doing that. Expose your own API to update the user data or whatever. Then the server should compose the SQL command and access the database.

wicked cairn
#

Ill write it as web request I guess. I just wanted shorter code lol

#

But yea I have a web server and dedicated host. I need the sql data to go between the host and game

teal viper
#

Let's build a nuclear rocket silo, but put the launch button on the wall outside, because it's more convenient - it saves us time entering the facility.

teal viper
#

Nevermind that anyone walking by can press the button.

frozen mantle
#

anyone have experience with convex mesh colliders with Rigidbodies attached to them causing some weird issues?

teal viper
#

What issues?

wind phoenix
#

i am facing issue with coin reset

#

it doesnt go back to 0

#

after run is over

#

this is my coin script

rich adder
#

because its static

wind phoenix
#

how to fix that?

rich adder
#

make it not static or explicitly set it to 0

frozen mantle
# teal viper What issues?

so, i fixed it by just removing the RigidBody (idk why it was attached to my health pick up in the first place...) but im curious as to what caused the issue.

Basically, i have a health pick that has a mesh Collider attached to is set to Convex and also is a trigger. I have the follow script attached to it as well (https://gdl.space/neloxorafo.cs), and the aforementioned rigid body. basically, when the player would walk over the health pick up and they are on full health. the pick up would stay there as intended, but when I look down and therefore have my viewModel gun start touching it, it starts to throw a NullReferenceException on line 43 of my script. This issue goes away when i remove the rigid body. I was just curious as to what was causing the issue in the first place?

wind phoenix
#

xD

frozen mantle
#

and why is it static in the first place?

rich adder
#

probably because they don't know how to properly pass variables with references

summer stump
frozen mantle
#

idk how experiences of a programmer you are, but maybe you can find some useful information in the article above

#

Static is a pretty specific modifier to use, and has alotta weirdness to it

frozen mantle
#

i would probably just do something dumb like CollactableControl.coinCount = 0 or something

frozen mantle
wind phoenix
#

after i make variable non static

#

it shows reference required

rich adder
#

yes so make a reference

wind phoenix
#

i have script named

#

otherscript

#

and reference to collectablecontrol script

#

still it shows error

rich adder
final hamlet
#

hello, i'm working on a tower defense game and want to make the tower's collider change according to its range since i'm using it for enemy detection. how would i go about setting the collider size once the tower prefab is instantiated?

wintry quarry
final hamlet
#

like that?

summer stump
wintry quarry
#

or alternatively there's no reason to use GetComponent it it's a public member variable since you can assign it in the inspector

final hamlet
#

the idea is that once a tower is upgraded, its range can increase. or can i just directly call the collider and increase it without the variable?

#

im a bit confused by what you mean by inspector

wintry quarry
#

well if you will use the reference multiple times, it's good to have the variable

#

however you should decide whether it's going to be assigned in the inspector or just with GetComponent

#

if you're using GetComponent there's no reason for it to be public

final hamlet
wintry quarry
#

It gets a component from the GameObject, yes

#

what's confusing you exactly?

final hamlet
#

as in assigning the size?

wintry quarry
#

The only reason to use public on your variable is if:

  • You want to assign the variable in the inspector
  • you want to access this reference from another script
#

neither of those seem to be the case here

#

so you should remove public from the variable

#

public SphereCollider detectionZone;

final hamlet
#

ahh i see

#

i understand that theres no need for detectionZone to be public now, but is there really any need for it in the first place? or can i just access the collider size directly via the gameObject

wintry quarry
#

Wdym by "directly via the gameObject"

final hamlet
#

i think im just getting tripped up by how gameobjects and their components work

final hamlet
wintry quarry
#

Saving the reference in a variable means you don't have to call GetComponent repeatedly which is both ugly and bad for performance

final hamlet
#

ahh okay, that was gonna be my next question

#

thank you

wind phoenix
#

but at end of my run is over panel it shows 0 coins

#

nvm fixed thanks guys @rich adder @frozen mantle

sullen rock
slender nymph
#

at no point does it reference a prefab

sullen rock
#

the _product.GO is a prefab

slender nymph
#

okay, but yet you do not pass the Product instance a reference to a prefab anywhere in the code you've shown

sullen rock
#

I know and thats what´s confusing me

slender nymph
#

how do you know the instance you created references a prefab?

sullen rock
#

I am trying to disable colliders later down the line by looping through the thisSectionProducts list and it is editing the prefabs themselves

#

also, inspectors shows a reference to the prefab, not the instantiated object

slender nymph
#

then you're looking at the wrong instance of the Product struct

sullen rock
#

I am pretty sure I am not

slender nymph
#

and i'm pretty sure you're wrong

#

show the relevant code where you are actually experiencing this behavior

sullen rock
#

there it is adding the product instance with the prefab as reference to the list I am looping through

keen dew
#

You can use AI as much as you want with your own projects. Coming here and trying to "help" other people by copy-pasting garbage from ChatGPT is not allowed. Or asking for help with code that was entirely AI-generated.

slender nymph
near yarrow
#

how to deselect inputfield when character is mvoing?

timber tide
#

I forget if it's an event, or if it's strictly on the inputfield, but there's some active element variable you need it switch off

night mural
#

probably you didn't actually follow the tutorial exactly!
make sure you made IInteractable an interface and not a class

astral topaz
#

I follow everything.

static cedar
#

I think interface is a reserved keywork. UnityChanThink

#

Ur trying to make interface a method name?

night mural
#

yeah that should error

#

configure your IDE

static cedar
#

Also interface type is coloured green, that's probably Visual Studio Code.

night mural
#

and the method should be called Interact...but maybe they were trying to follow my advice by randomply replacing text with the thing i said and it wasn't like that before

astral topaz
#

hmm but already installed this

#

the unity extension aswell

#

like 2 years ago

eternal needle
astral topaz
topaz mortar
eternal needle
# astral topaz i dont have that

intellisense isnt the name of an extension, its just your IDE helping you autocomplete and provide you info about stuff like methods

#

you may have to update, there was some new development for unity and visual studio code

astral topaz
topaz mortar
#

mate just save yourself the headache and install Visual Studio instead

astral topaz
#

ok

eternal needle
# astral topaz

i didnt mean vscode itself. the unity extension was updated but it seems like your c# extension wasnt working either. i do as well think visual studio is just better if you are willing to swap

astral topaz
#

im going to swap since i dont really have time to fix vs code

acoustic sequoia
#

HI, I seem to be having issues with something very simple.

OntriggerEnter2d and OnCollisionEnter2d are not working. after following a few tutorials on youtube. it still doesnt work. anyone care to help?

hollow zephyr
acoustic sequoia
#

@keen dew lol this does not help

verbal dome
acoustic sequoia
#

@verbal dome I'm still looking through it but it's not helping

verbal dome
acoustic sequoia
#

Ok so now it's working? and i didn't do anything to change it.

#

does it matter if the collider is above the rigidbody in hierachy?

verbal dome
#

Yes

#

Collider has to be on the same object as the rigidbody or one of its children

acoustic sequoia
#

i had the collider above it and it wasnt working. switched it and now it works...

#

no, i mean above it on inspector

verbal dome
#

Inspector order dont matter

acoustic sequoia
#

wait wtf, its not working again!?

#

i'm not even changing anything

queen adder
#

you are aware that you are the only one seeing your problem, are you?

acoustic sequoia
#

I don't even see my problem..

#

ok so now it is working but when my player enters the trigger it is pushed back out?

slender nymph
#

show the inspector for both of the objects and any relevant code

rare basin
#

How can I change the speed of this animator "node" through code?

slender nymph
#

if you leave Speed at 1 you can set a parameter for a multiplier and just change that parameter

topaz mortar
#

probably not a code question, but what would I use to make my item hover window always appear on camera (when the items are near the edge) and are always in front of everything?

rare basin
#
    public void SetStatistics()
    {
        attackPower = owner.unitData.attackPower;  
        defencePower = owner.unitData.defencePower;
        moveSpeed = owner.unitData.moveSpeed;
        attackCooldown = owner.unitData.attackCooldown;
        attackRange = owner.unitData.attackRange;
        owner.animator.SetFloat("MoveParam", owner.unitData.moveAnimMultiplier);
        Debug.Log($"{owner.unitData.unitName}: {owner.unitData.moveAnimMultiplier}");
    }
#

It prints 1 in the console

#

But shows 0 in the parameters tab

#

And the movement animation indeed uses 0 speed, animation doesnt play at all, stuck at 1st frame

rich adder
rare basin
#

I did

#

Im not selecting it from assets files

rare basin
#

owner.unitData.moveAnimMultiplier is not 0

slender nymph
#

are you certain you are calling SetFloat on the correct Animator instance?

#

and that nothing else is assigning to it?

rare basin
#

nothing else, im not modyfing the value anywhere else

slender nymph
#

show all of the relevant code instead of these tiny snippets. you aren't showing enough context to know for sure what the actual issue is

rare basin
#

okay wait

edgy timber
#

i have a doubt
void OnMove(InputValue value)
{
moveInput = value.Get<Vector2>();
Debug.Log(moveInput);
}
in the first line the value from OnMove is getting stored into the "value" of type InputValue right?

rare basin
#

i think i might have referenced the prefab

slender nymph
#

at a guess i'd say you have a reference to the wrng object somewhere

rare basin
#

instead the Unit in hierarchy

slender nymph
#

yeah that'll do it

slender nymph
edgy timber
#

got that but am i right about the first line?
void OnMove(InputValue value)

rich adder
#

It exists so that action callback data can be represented as an object, can be reused, and shields the receiver from having to know about action callback specifics.

edgy timber
#

thats not what im asking... im trying to get my head around how functions work...

rich adder
edgy timber
#

im asking if the data created in the OnMove function(unity input system) is getting stored into the parameter "value" of type InputValue which is later assigned to "moveInput".

slender nymph
edgy timber
#

yes or no would have been more helpfull.....

rich adder
#

it can be named joe for all it matters, the value is the same

#

should def do some beginner c# courses though

edgy timber
#

then the next line would be
moveInput = Joe.Get<Vector2>();
?

rich adder
#

yup

#

parameter names don't affect the underlying object/data

edgy timber
#

thats all i wanetd to know... phew....

cloud flume
#

anyone know how i could make it so i dont need to leave the ants hit box and come back again just for it to do more damage? i want it to continuously do damage while colliding

#

my taking damage code

slender nymph
#

OnCollisionStay2D

#

you'll probably want to add some sort of cooldown though

stiff stump
#

Hey i have an issue with raycasting an im not sure why I am casting my ray here

float distance = Vector2.Distance(transform.position, target.position);
RaycastHit2D hit = Physics2D.Raycast(transform.position, target.position, distance, _obstacleLayer);
Debug.DrawLine(transform.position, target.position);

Debug.Log(hit.collider);

and hit.collider is returning null
but when i draw my ray it is hitting the collider and the "wall" is on the obstacle layer

cloud flume
rich adder
stiff stump
#

ah got it working thanks 🙂

ruby python
#

Is there a way to get an object to get the position of an object that is directly in front of it, but with a varying Y position?

teal viper
#

Could get all potential objects, then do a dot product on vector2s

cloud flume
#

right now i have a script on my character detecting if he collides with the enemy he takes damage, shoud i make it so the enemy has the damage on its script instead?

ruby python
#

@teal viper Cool, thanks, will take a look 🙂

strong wren
ruby python
stable jackal
#

in my fps game i set my cursor to

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

and when i change scenes i can't seem to click buttons if i press escape, then if i click back, its as it's still locked, how do i unlock it?

silk night
stable jackal
#

is there a line of code where i can just "unlock" it?

silk night
#

Its basically the same you already did, just another CursorLockMode and visible needs to be true again

stable jackal
#

ah okay thank you

queen adder
#

Hey i have there a question about the createion of texture2D. is it possible to create the texture via code and mark it as read-writeable?

swift crag
#

By default, this is false for texture assets that you import into your project. To toggle this, use the Read/Write Enabled setting in the Texture Import Settings, or set TextureImporter.isReadable.

By default, this is true when you create a texture from a script.

lilac crow
#

hi @swift crag ! its me again.
i just applied gravity to my character and its speed got slow like very slow.
i change the speed to somthing higher but it did nt change much.
any idea how to fix it?

swift crag
#

Show your code.

#

I can't guess what you've done

lilac crow
#

HEHE my bad !

#

ill send it

lilac crow
swift crag
#
Vector3 direction = new Vector3(horizontal, gravity , vertical).normalized;
#

Here is your culprit.

#

You're normalizing that vector, so its length is always 1

#

gravity is -9.81, so the vector will wind up being almost entirely pointing in the Y direction.

#

You should calculate the velocity you get from your movement input

#

Then also calculate your velocity from gravity

#

Then add the two together.

#

Also, this is not the correct way to do gravity: you should be accelerating by -9.81 m/s per second

#

So, take your vertical velocity from the last step and add -9.81 * Time.deltaTime to it

#
Vector3 movement = Vector3.ProjectOnPlane(controller.velocity, Vector3.up);
Vector3 gravity = Vector3.Project(controller.velocity, Vector3.up);
#

This separates the old velocity of the controller out into the movement part and the gravity part

lilac crow
#

got it !
oh this dummy have a othe question!

swift crag
#

ProjectOnPlane removes the part of the first vector that aligns with the second vector
Project removes the part of the first vector that doesn't align with the second vector

lilac crow
#

transform.rotation = Quaternion.Euler(0f, TargetAngle, 0f);

#

i did this

#

but

#

when i use A and D

#

my character wont turn

#

i did the sam as this tutorial

swift crag
#

you used the wrong conversion factor

#

Mathf.Atan2 returns radians

#

you used Mathf.Deg2Rad

lilac crow
# lilac crow i did the sam as this tutorial

Let's learn how to make a solid third person controller with a moving camera!

Jason no longer offers the course mentioned in the video.

👕Get the new Brackeys Hoodie: https://lineofcode.io/

● Third person controller asset: https://assetstore.unity.com/packages/templates/systems/third-person-controller-126347?aid=1101lPGj

·····················...

▶ Play video
swift crag
#

so that made the resulting angle even tinier, since Deg2Rad is going to be 2 * pi / 360

wintry quarry
#

Also why is direction made of the horizontal input and gravity?

swift crag
#

that should be separated, yes

wintry quarry
#

Also x and z are reversed in the atan2

lilac crow
swift crag
#

i think they were backwards last time too

#

I prefer to not do any trig

#
Quaternion.LookRotation(direction);
#

this produces a rotation that makes you look in that direction

lilac crow
#

i should report this toturial .
so many wrong doings in it!

swift crag
#

Here is how I usually do this kind of thing

lilac crow
# swift crag Aeugh

well that wasnt in the code he wrote untill where i need it 😁😁😅😅😅😅😅
dummy me!!!!!!!!!!

swift crag
#
Vector2 moveInput = moveActionRef.action.ReadValue<Vector2>();

Vector3 localMove = new Vector3(moveInput.x, 0, moveInput.y);
Vector3 worldMove = Camera.main.transform.TransformDirection(localMove);

worldMove = Vector3.ProjectOnPlane(worldMove, Vector3.up);

worldMove = worldMove.normalized * moveInput.magnitude;

The last few lines are necessary because the camera might be pointing up or down, so worldMove will wind up with some up-and-down value. Projecting it with the Y axis fixes that, but that makes the vector shorter. So, I normalize it and multiply it by the original move input's magnitude.

lilac crow
#

@swift crag i think i got it. i try to make it.
sorry to make you annoyed every time.
to be honest it only two weeks since i started to learn unity and c#.

gilded cradle
#

Hey I was working along with a video guide for 2d platformer movement and I seem to have the same thing as the guide yet I am unable to move, anyone willing to help out? (:

#

my settings in unity and the 2 scripts seperated by a big line in the pastebin for info

somber wren
#

and "FixedUPdate"

gilded cradle
#

I have nothing set as ground but neither did the video as far as I know

#

I just got a tilemap collider

#

Ah the UPdate seemed to be the thing messing it up

pseudo sable
#

it's probably the FixedUPdate, c# is case sensitive so FixedUPdate won't be called

#

doesn't complain about duplicated method

somber wren
#

any idea on why no of the rays (displayed in red here) detects anything (here is the little code)

#

the debug.log doesnt show anything

pseudo sable
#

are the two things you want to collsion detect on the correct layer?

#

(or at least, the wall is on the correct layer as defined by layer)

somber wren
#

everything is on default

#

here is the call of the function

pseudo sable
#

and silly question but the wall has a collider yeah?

somber wren
#

it detects none of them

sterile river
#

Concerning the camera and its rotation I have a question. what do camerarotation.yaw/pitch do? I found some code in tutorials but it wasn't explained very well 😅 Thats why i wanted to ask you guys

pseudo sable
# somber wren yes, and the ground too

is your vehicle in motion or is it just sitting next to the wall? one thing i can think of is that raycasts don't detect colliders if the origin of the ray is inside the collider so if one ray ends right at the last pixel beside the collider, and the next one starts inside, there won't be a hit detected

#

if you're moving the arc in and out of the collider and it's still not working then it won't be that

somber wren
#

its moving

#

i moved it next to the wall with my controller

pseudo sable
#

hmm won't be that then

somber wren
#

it was working at a point but i cant remember what i changed

#

okay apparenly the "0" in the layer parameter was messing up

#

okay its working, now i have the problem of my body distance from the ground lmao

spiral oak
#

Hi, this is just a dumb question.
If Im creating a tool, should its assembly have my name in it? How usually tool developers name their assemblies?

sturdy lintel
#

Hey guys, quick help. I have a LineController.cs script which is attached to LinePrefab as:

using UnityEngine;
public class LineController : MonoBehaviour
{
    private SlidersWithEcho slidersRef;
    private Vector3 startPoint, endPoint;
    private string lineType;
    private GameObject TBall;
    public GameObject TravelingBallPrefab;
    private float speed = 6f, lifeSpan = 10f, spawnInterval = 1f, lastSpawnTime;

    void Start()
    {
        slidersRef = GetComponent<SlidersWithEcho>();
        lastSpawnTime = Time.time;

        if (lineType == "AimLine")
        {
            TBall = Instantiate(TravelingBallPrefab, startPoint, Quaternion.identity, this.gameObject.transform.parent.transform);
            TBall.GetComponent<TravellingBalls>().UpdateTravellingBallsDirection(startPoint, endPoint);
        }
    }

    void Update()
    {
        if (lineType == "AimLine" && (Time.time - lastSpawnTime) > spawnInterval)
        {
            lastSpawnTime = Time.time;
            TBall = Instantiate(TravelingBallPrefab, startPoint, Quaternion.identity, this.gameObject.transform.parent.transform);
            TBall.GetComponent<TravellingBalls>().UpdateTravellingBallsDirection(startPoint, endPoint);
        }
        else if (lineType == "AimLine" && (Time.time - lastSpawnTime) > lifeSpan)
        {
            Destroy(TBall);
        }
    }

    public void AssignGameObjects()
    {
        endPoint = this.transform.parent.Find("EndPoint").gameObject.transform.localPosition;
        startPoint = this.transform.parent.Find("StartPoint").gameObject.transform.localPosition;
    }
}

I have another script where I manipulate 3 sliders intervalSlider, speedSlider, timeSlider. In above script if I do the below, it throws NullException Error. Moreover I cannot even drag drop the sliders script reference in editor.

if (lineType == "AimLine" && (Time.time - lastSpawnTime) > sliderRef.intervalSlider.value){}
tender terrace
#

is there a way to make this plane controller more precise cause it takes the slightest input and adds the torque to the plane and the whole thing becomes uncontrollable

languid spire
silk night
tender terrace
#

yes, something like that

queen adder
#

Basically i moved all my scripts to another folder and now its says this ☃️

silk night
languid spire
queen adder
tender terrace
oak epoch
#

Why do I get "The associated script can not be loaded" on my components after I move their script to a folder named "Editor"?
That's what you are supposed to do with code that touch thing like AssetDatabase, no?
Tried reloading, rebooting, etc. Moving them out of "Editor" folder fix the problem but then I can't build anymore.

crude prawn
#

Input.touch is only for mobile users right? Is there one where i can use for both pc and mobile users?

sick raven
#

Guys, good day :3
Sorry for the stupid question, I'm a newbie game developer ❤️
What's the best way to design level changes for indie platformers? is there any guide? Is it better to do this on one stage or create several for each level?

silk night
silk night
oak epoch
#

... yes? I'm talking about using them in-editor.

silk night
silk night
crude prawn
#

oh wait yeah thank you

silk night
oak epoch
crude prawn
#

and then use line renderer to show outlines where u dragged

silk night
#

Alright, if you want drag look at IDragHandler, IBeginDragHandler and IEndDragHandler

#

they give you an easy way of handling drag

oak epoch
#

They work only if I move them out of Editor folder.
I can build only if I put them in.
Would like to have both because it's annoying to move scripts around anytime I need those script to generate assets and when I need to build.

silk night
blazing prairie
#
{
    public BigDouble GoldValue { get; set; }
    public void IncreaseGold(BigDouble val) => GoldValue += val;
    public void DecreaseGold(BigDouble val) => GoldValue = BigDouble.Max(0, GoldValue - val);
}``` Is this code OK ?
oak epoch
#

Wait, really?
Weird design.
Guess I'm just gonna spam #if UNITY_EDITOR then.
Thanks for the answer.

polar acorn
silk night
oak epoch
#

Those ones take a "raw" model, clean up the skeleton, switch material to optimized one, then generate several version with different LOD & settings, then save all of that as prefabs that can be used in the game's actual scenes. The scene they are is never part of any build.

silk night
#

If you already have Odin installed - even easier

oak epoch
#

I used to use custom editor window but it's so much boiler plate code compared to just [ExecuteInEdit] + using a boolean as "button" in the Update loop.
I'm aware this is dirty practice, but it's just so much more practical (outside of the conflict with Editor folder).

silk night
#

Do you have Odin by any chance? If so its fairly easy

oak epoch
#

Never heard of it. Will check it.

oak epoch
#

Guess I will stay with my solution then, but thanks for the suggestion.

silk night
#

Even then you might want to create a custom window, even without odin its not that bad to create one

crude prawn
#

Can anyone help me with my line draw? im trying to get the effect of where ever the player is dragging there will be a white outline to show where the player dragged. https://pastebin.com/CSUwJsEq

muted wadi
#

does anyone know how to reference a specific object within a hashset?

peak siren
#

I have a question. What are good resources for learning to code. I am having a hard time retaining stuff with coding. Tutorials do not really help as all I be doing is just copying what someone is doing and most tutorials online does not really exaplin why things are the way to do things or give challenges and such to help retain that information. They are great for breaking ground on some information and features but not good for reatiner and longer term learning. I just been getting frustrated as when I get into the engine and try to solve a problem with a feature or some idea I have for a part of a project and just hit a roadblock because I do not know how to get to the point of problem solving in the code side of things

gaunt ice
#

!learn, and probably learn c# from the most basic (console.writeline("hello world")

eternal falconBOT
#

:teacher: Unity Learn

Over 750 hours of free live and on-demand learning content for all levels of experience!

muted wadi
# peak siren I have a question. What are good resources for learning to code. I am having a ...

I'm struggling with something similar, I recommend breaking down the problem into smaller, manageable steps. Take your time when trying to figure out what you want to make happen and don't rush. Rushing is what makes you hate coding because you feel like you're not doing anything, when in reality you're looking at the smaller pieces and putting them together. Another tip is to just code, don't worry about whether or not its fancy or well written, just code something slowly until it works.

peak siren
muted wadi
#

you're overthinking it. Start off with the most basic thing you need in your script. Do you need a float, do you need a bool, do you need a reference to a separate game object?

#

dont try to imagine the entire house in one go, start with the foundations

peak siren
#

well i know the differences of the operators and how to do variables and things like that its just like taking those and making something function that i need it to do like i am even keep forgeting on how to do basic player movements for an example

muted wadi
#

i recommend reading Unity Documentation if you're not sure where to start on making something function. They have a detailed example there that you can work off

#

they have great examples for stuff like .position, .rotation and many others

#

and again a lot of people forget code that they've written for stuff, i check back on old projects a lot just to remember how I solved a certain problem

uncut dune
#

Ive got a unity event comming from my the same gameobject and sometimes I get an error when it gets destroyed

#

how do I even check if it gets destroyed

uncut dune
#

like if(gameobject != null) ??

silk night
topaz mortar
#

how do I make a UI element always appear on top of everything else?
it's an item description, nested pretty deep
is there a component that can do this?

uncut dune
#

the gameobject u put on the bottom

#

is the one on top of everything

#

and the one on top is the one on the bottom of everything

#

so if u want to make something appear on top of others just put it in the bottom in the hierarchy

silk night
uncut dune
#

not sure if there is a better way

uncut dune
silk night
uncut dune
silk night
uncut dune
#

the second method

#

is the special effect

#

how do I check if the object is destroyed

#

or gets destriyed

muted wadi
#
{
    transform.position += Vector3.down * Time.deltaTime * fallSpeed;
}```
is this considered teleporting or is the object moving properly?
muted wadi
#

damn

uncut dune
silk night
#

If you want to emulate physics movement, add a rigidbody and either use MovePosition or AddForce on that

silk night
uncut dune
#

exactly if u want to do by changing the transform use MovePosition or Lerp

uncut dune
muted wadi
#

its not that i want to emulate physics, i just want the collider to interact properly with the istrigger

silk night
#

collider = physics

muted wadi
#

thats not what I mean

silk night
#

The Physics System is what resolves the interaction between the collider and the trigger

muted wadi
#

im wondering if an object enters a collider, teleports further inside the collider, does it mess up the ontriggerstay method?

uncut dune
#

yah and to trigger something one of the objects must have a rigidbody

silk night
#

So yeah, add a Rigidbody and use the Rigidbody.MovePosition

muted wadi
#

it already has a rb

silk night
#

Then reference it in script and move it via that

uncut dune
#

exactly

muted wadi
#

alright

grizzled roost
#

i were downloading unity then it stucked here

#

i got notification from antivirus that said it been blocked

#

how do i unblock it

restive badger
#

Start Unity hub as administrator it generally fixes the issue

#

If it doesn't work you might want to change the download location these are the most common solutions in my experience

uncut dune
#

I still get the error

#

hmm maybe its something else

restive badger
#

Click on the error log twice and it will lead you to code where it causes the error

bitter carbon
#

is it possible to call a function/method from one scene then define it in anotrher scene

wintry quarry
#

scenes are not a concept in C#

bitter carbon
#

yea but in another class in anotehr scene

wintry quarry
#

you can indeed get references to objects in other scenes and call functions on them, no problem

bitter carbon
#

ok

muted wadi
#

what is the difference between - and -=

wintry quarry
muted wadi
#

thank you so much

#

that makes so much more sense than the drivel i've been reading

restive badger
#

these both will do the same thing

edgy fox
#

how would I add a global dictionary accessible from all other scripts (essentially, a lot of scripts will need to access variables such as selectMode and similar variables)

heady nimbus
#

Weird collider question:

I've got a player object with standard capsule collider and a script "KnockBack" on it that handles getting knocked back when colliding with an enemy object.

I'm working on creating a melee weapon attack (2d) for this player now. I created a script for it, and a basic weapon prefab with its own collider set to trigger that I instantiate on input (As child of player), and destroy shortly after.

The issue I'm having is the weapon prefab collider is now being treated as an extension of the player collider, triggering the knock back script.

edgy fox
gaunt ice
#

static modifier

edgy fox
gaunt ice
#

though i dont recommend your design unless you are experienced in coding or you have experience in non OOP language
it allows you to access variables/methods without instance reference since static variable is belong to the class not the instance

restive badger
bitter carbon
heady nimbus
edgy fox
#

So essentially, if I have a variable roomSelected stored as false in static class A, and class B sets roomSelected to true, class C sees it as true

#

and in that case, what is the syntax for modifying variables in a static class from another script?

bitter carbon
#

@wintry quarry

gaunt ice
wintry quarry
heady nimbus
# restive badger you can use tags or layers to make that collider ignore your player

Oh jesus... I set the wrong collider to ignore the weapon... Enemy has 2 colliders since I didn't want them to use physics vs the player, but still wanted to use physics when interacting with the world... The one that's supposed to interact with the player is now ignoring the weapon and it's working, thanks for getting me to double check those

wintry quarry
bitter carbon
wintry quarry
#

to access a static variable in a class you do ClassName.VariableName

wintry quarry
#

functions go on classes

#

you need a reference to an instance of a class to call a function

#

so someReference.DeathScreenFunc();

bitter carbon
#

what is the reference,

wintry quarry
heady nimbus
# bitter carbon what is the reference,

I think you need to go back to basics on creating classes and how to reference 1 class from another class. What you're saying about "funciton on a different scene" doesn't make sense

wintry quarry
#

Yep, this is literally Unity 101 "referencing scripts" stuff

#

do some basic tutorials

bitter carbon
#

ik how to reference scripts but i didnt know if u had to reference scene or smth

wintry quarry
#

To do it between scenes you may need some techniques like Singleton or dependency injection or FindWithTag but that's not a huge hurdle

bitter carbon
heady nimbus
#

Are you trying to reference a script on a game object in a dfferent scene?

wintry quarry
#

learning requires error

#

trial and error

#

It's a process

bitter carbon
#

ima ask chat gpt as it has manners and is actually smart

restive badger
#

lol

bitter carbon
#

and answers to what i asked

heady nimbus
#

Holy moly

bitter carbon
#

and listens to what i said

polar acorn
heady nimbus
#

We did listen. what you said doesn't make sense

muted wadi
polar acorn
#

You just don't know what "reference" means because you've skipped the basics

bitter carbon
muted wadi
wintry quarry
muted wadi
#

sure

wintry quarry
#

Also do some debugging steps

bitter carbon
bitter carbon
heady nimbus
bitter carbon
#

it does to me

#

and im sure chat gpt will know as well

muted wadi
#

script for the cubes to fall

{
    [SerializeField]
    float fallSpeed = 1.5f;
    [SerializeField]
    Rigidbody rb;
    [SerializeField]
    Vector3 current;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        current = rb.position;
    }

    private void Update()
    {
        rb.MovePosition(transform.position - Vector3.up * Time.deltaTime * fallSpeed);
    }
}```
polar acorn
heady nimbus
#

But it doesn't make sense as it relates to Unity development. So you're making up scenarios that no one else understands and getting mad while we try to decypher your bad use of terminology

muted wadi
#

script for checking when the pinks enter the reds and to destroy them

{
    [SerializeField]
    KeyCode keyToPress;

    Color pressedCol = Color.white;
    Color unPressedCol = Color.red;
    [SerializeField]
    Renderer rend;

    private void Start()
    {
        rend = GetComponent<Renderer>();
    }

    private void Update()
    {
        if (Input.GetKeyDown(keyToPress))
        {
            rend.material.color = pressedCol;
        }

        if (Input.GetKeyUp(keyToPress))
        {
            rend.material.color = unPressedCol;
        }
    }

    private void OnTriggerStay(Collider other)
    {
        if (Input.GetKeyDown(keyToPress))
        {
            Destroy(other.gameObject);
            DDRManager.Instance.score += 1;
            DDRManager.Instance.score += 1;
        }
    }```
wintry quarry
#

you cannot do input handling in physics callbacks

#

physics don't run every frame

muted wadi
#

ah

wintry quarry
# muted wadi ah

You need to do something like this:

List<Collider> currentNotes = new();

void OnTriggerEnter(Collider other) {
  currentNotes.Add(other);
}

void OnTriggerExit(Collider other) {
  currentNotes.Remove(other);
}

void Update() {
  if (Input.GetKeyDown(whatever)) {
    foreach (Collider note in currentNotes) {
      DestroyAndAdjustScore(note);
    }

    currentNotes.Clear();
  }
}```
muted wadi
#

AHHHHH

wintry quarry
#

Basically keep track of all the notes currently in the zone and when you press a key then you destroy them

#

with input handling done in Update

muted wadi
#

i was trying to do that with HashSet but i didn't get how

wintry quarry
#

but didn't want to confuse you

#

you can just replace List with HashSet in my example and it will work fine

muted wadi
edgy fox
opal fossil
#

Is Unity moving to .net core anytime soon?

wintry quarry
edgy fox
#

ah fun

summer stump
# bitter carbon and im sure chat gpt will know as well

You complained about being set up for error, but then say you're going to use GPT, a spam generator that will happily lie to you.

I say this as someone truly trying to help, but the people here were giving you good and helpful answers. GPT will lead you astray unless you ALREADY know enough to filter the lies from facts.

heady nimbus
#

If more than 1 collider triggers an OnTriggerEnter event, are they handled simultaneously? Or is it only going to trigger on one then, then MAYBE the other (think melee weapon attack striking out at 2 enemies at once)

bitter carbon
summer stump
#

You were rude to their responses

wintry quarry
bitter carbon
#

they said do u know what a reference is, when i was 7 years old i knew that

summer stump
heady nimbus
bitter carbon
muted wadi
heady nimbus
bitter carbon
#

neither did the other person

wintry quarry
#

note is just a local variable inside that one for loop

#

it is not used nor needed to be used anywhere else

muted wadi
#

oh ok

#

i was just confused

#

i thought you were using it in another method outside the loop

wintry quarry
#

nope

muted wadi
#

since the method is called DestroyAndAdjustScore

#

is it possible to do that though?

wintry quarry
#

Oh yes - i'm passing that to a function

muted wadi
#

i guess if i declared it separately

wintry quarry
#

Yes you would have to declare that function somewhere

#

the idea of that function is to do what you have here:

            Destroy(other.gameObject);
            DDRManager.Instance.score += 1;
            DDRManager.Instance.score += 1;```
#

but ofc you'd destroy the parameter's GameObject

muted wadi
#

wait why does it say score twice

wintry quarry
#

you wrote that code not me lol

muted wadi
#

shit that's supposed to be combo not score

wintry quarry
#

inside AddScore you can increment the score and the combo

muted wadi
fossil tree
#

hi what is the void for check the condition when my checkbox are checked?

#

idk if i explain good so sry for my bad english

cyan wigeon
#

Anyone knows why this prints out "Has Internet"

   public void SaveSettings()
    {
        Debug.LogWarning("Saving Settings!");
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            GameManager.instance.HasConnection = false;
            Debug.LogWarning("No Internet!");
        }
        else
        {
            Debug.LogWarning("Has Internet!");
            GameManager.instance.SaveCloudGameData();
        }

        if (!GameManager.instance.HasConnection)
        {
            menu.ErrorConnectionPanel.SetActive(true);
        }
        
        menu.MainMenuBtn();
    }

When I turn off my connection?
I am trying to create some error popups and for some reason when I build EXE
if (Application.internetReachability == NetworkReachability.NotReachable)
steps into else when I turn internet connection. It works fine in unity engine
any ideas ?

gaunt ice
#

i think you mean method not void

fossil tree
wintry quarry
fossil tree
#

oh ok

#

because if i not put void that return anything?

#

and i talking about the toogle checkbox

wintry quarry
heady nimbus
#

void describes the return type, void functionName() specificaly means returns nothing. int functionName() means it would return an int value, etc.

As for the check box, are you talking about the UI Element check box, or something in the inspector?

fossil tree
#

the ui element check box

fossil tree
#

this

rich adder
warm raptor
#

ok so instead of using a find methode that is apparently cursed will it be better to use "public static float"

fossil tree
#

what is the protected override thing

#

before void

#

sry im a newbie

rich adder
rich adder
muted wadi
#

can an object not be destroyed by OnTriggerExit?

wintry quarry
#

they can

muted wadi
#

thats weird

wintry quarry
#

why not

muted wadi
#

this is meant to destroy the object if it leaves the collider, but it doesn't

{
    notesInside.Remove(other);
    Destroy(other);
    notesReady = false;
    SubtractScore();
}```
wintry quarry
#

not the GameObject

muted wadi
#

i also did other.gameobject and it didn't work

wintry quarry
#

How do you know it didn't work?
Did the code run?

rich adder
muted wadi
#

uhhh

#

OnTriggerEnter is working so this should also be working

fossil tree
#

protected override void OnEnable() why that make me a error?

muted wadi
#

ah sorry guys i was dumb

#

forgot to add .gameobject to another function

rich adder
wintry quarry
fossil tree
#

oh override is for a already exsting method ?

wintry quarry
#

no it's for overriding a virtual or abstract method on a parent class

#

I don't really know where you saw that from or why you're trying to use it

fossil tree
#

i see that on the doc xd

wintry quarry
#

which doc

fossil tree
wintry quarry
#

why are you looking at that

rich adder
fossil tree
#

idk

wintry quarry
#

ignore the rest

cyan wigeon
wintry quarry
# fossil tree idk

also this is to show you the property that exists already on Toggle. This is not code you are supposed to write. This is code you interact with

#

it means you can do bool isToggleOn = myToggle.isOn;

rich adder
cyan wigeon
rich adder
#

yea kinda something like that

cyan wigeon
#

ye what confuses me it works like a charm in editor but not in build

rich adder
#

seems like others had the same issue 🤷‍♂️

#

few people mentioned doing what I did with the webrequest

cyan wigeon
#

ngl annoying xd

fossil tree
#

ok i can define him if he are on or off but how i can use that after?

bitter carbon
#

For some reason the 2nd one gets disabled but the first one doesnt get anabled, if anyone can help and needs extra info lmk

uncut dune
#

wut

wintry quarry
wintry quarry
uncut dune
#

quick restart might fix

muted wadi
#

what happens if you set a variable to public but also serialise it?

wintry quarry
#

public variables are already serialized

muted wadi
#

oh ok

wintry quarry
#

There are two ways to make a field serialized:

  • make it public
  • mark it with [SerializeField]
muted wadi
#

that makes sense

wintry quarry
#

doing both won't make it "double" serialized or something

muted wadi
heady nimbus
#

Alright, I botched these collider interactions, looking for some suggestions to fix

Player has Rigidbody + collider

  • also spawns in melee weapon with its own trigger collider

Enemy has Rigid body + collider, set to exclude player and weapon (this is basically just for physics and ground collision)

  • has child object with just a trigger collider that interacts with player (damage and knock back purposes)

Trying to get the weapon to interact with the enemy collider, but for some reason the weapon collider is triggering the OnTrigger from the knockback logic on the player

rich adder
#

also check console for runtime errors?

bitter carbon
#

i think there is none ill cehck again thgough

#

yea there is no errors

rich adder
fossil tree
#

hm litlle question more how i can make to put my game into full screen i try this: Screen.fullScreen = true; but i dont think that work i dont see change in my screen

rich adder
#

I dont think fullscreen would work in editor build

fossil tree
#

so i need to build the game

#

ok x)

wicked cairn
#

Does yield return www.SendWebRequest(); pause if someone elses game build in the world is sending a request to the same url?

uncut dune
#

can a unity event not have a vector2 parameter?

rich adder
uncut dune
#

this doesnt appear in unity events

fossil tree
#

when i open my project i am in border i want when i put my setting in full screen my game go fullscreen that dont work with Screen.fullScreen = true;

uncut dune
rich adder
# uncut dune

Hmm yeah not sure, I don't use the inspector for events 😛
I prefer Action and do everything in code

uncut dune
#

I'll ask in unity tlk

#

talk

rich adder
wicked cairn
#

so I figure send it through web request or sql

#

but what if more than one lobby is made at the same time, right?

rich adder
#

everyone is running their own copy of the same game, they shouldn't affect eachother

wicked cairn
rich adder
#

so? websites servers deal with traffic on the same address

wicked cairn
#

game -> web host file -> server, port generated -> web host -> game

#

saved to a pre existing text file ig

rich adder
#

i mean yeah if you trust anyone can connect without validations in place..

wicked cairn
rich adder
#

oh just the port ? ok

wicked cairn
#

im just afraid that while one of the consoles sends a port info to the file, and another one sends it at the same time, then when the game goes to read it its grabbing the wrong port

#

or something.

#

because on the host server its duping the console program to create multiple open ports/hosts for each lobby

rich adder
wicked cairn
#

cant test it

#

unless I am able to read the file first and make sure its value is "empty"

rich adder
#

what if one person has slower internet / loses connection, does your server handle that?

wicked cairn
#

just wouldnt want a bunch of ppl waiting for other peoples request to finish

rich adder
#

just make them different async Tasks or separate coroutines no ?

#

that should create a task for each user

wicked cairn
#

its peer 2 peer multiplayer. I just have the server hosting the session

#

but of course each lobby needs its own port, so on a server I have a console program open itself to make a new port, after steam lobby is ready to play

#

however, somehow the game needs to know what the port is yea?

#

best way I can think of is either entering all those ports into a mysql database, or if a web request can do it without the same file interfering

rich adder
#

I suppose a list of available ports or something, when someone connects they take over that port. when they disconnect release the port back in the list

wicked cairn
rich adder
#

danggg here i am , just letting something like relay / lobby handle all this.

wicked cairn
#

I am using relay, with steam matchmaking

rich adder
#

oh Unity relay ?

wicked cairn
#

dedicated server is launching a console app that generates a port as a peer 2 peer host. all I need is in game if a player opens the game and joins matchmaking, how matchmaking would know to use that port

rich adder
#

ehh lol thats dedication right there.. I just let Unity handle it

#

i dont plan on having more than 50CCU right now so its all free for me

rich adder
#

if you got more than 50CCU monthly you dont want a self made system tbh

#

youd be able to probably afford their paid tier