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.
#💻┃code-beginner
1 messages · Page 42 of 1
you have to save the value of the PP Volume slider
we use something called caching and store each player we need somewhere and access them. But Idk what multiplayer you're doing that requires all this stuff. You're better off using at least Netcode and start there
Which part of your script is even multiplayer? Every multiplayer solution will have some way to sync transforms directly and what you're showing doesnt even do that.
This script just is constantly doing unnecessary Get and Finds
I'm using web socket and i made m'y own serveur
You shouldnt try to make your own solution unless you realllllly know what you're doing
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
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
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
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?
this is not what was mentioned yesteday @acoustic arch
why are you storing gameobjects
thats the most useless type to store in unity
oh
any script on a gameobject has reference to that object / transform
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
should it be the Slot component on the object?
well yeah because its a slot.
You still have 2 lists/arrays
but then how do i change the actual slots sprite to show it?
you have a reference to the image component on the slot via the Slot script
which gets it from the assets's SO
ah
the SO should store things like name, stats, info, and icons /sprites
yeah it does
so then yeah you're literally overcomplicating it with having 2 lists to manage n all that
Regardless of what you explain here, the script you wrote is not suitable for multiplayer because you are using Gameobject.find to look for the player. Once you have many players, this will not work.
Also you are doing the same .Find many times in one method, just cache the result because it's not gonna change between those lines of code
oh yeah well how do i do it instead with just one?
lol Like I said many times. It should just be a list of Slot
slot has all the info you ever need
Inventory deals with slots
it only means logical sense to have a List<Slot>
exactamundo
alright
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
yeah
which is a lot simpler than what i was doing beforehand
my code no longer looks gross
🙂 yea it helps when things are neatly encapsulated
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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;
}
}
}
!code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
its a custom script
then what is going on here
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
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?
what is Volume
so you couldnt ask for this earlier instead of just doing w/e you thought was correct 🤔
srry man
now you know
Ok I will try my best to optimise my code (btw i also tried with 3 people connected at the same Time and it work 😅)
anyway what exactly isn't working ? @alpine mortar
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?
that when I change scenes the brightness doesnt work and when I go back to options the brightness resets
also which slider are you chaning since this old processing is different
and no, i dont know how to use playerprefs
No I mean is it working when you slide it in the scene
because I dont see the Black Color from Color Adjustment
make a thread real quick
in the options menu it works
in other screens it doesnt
ok so save the value into PlayerPrefs or something like that
.
I've seen it in your script wdym you dont now how
I don't know how
you mean slider value instead of slideravalue?
void Start()
{
brightness.TryGetSettings(out exposure);
AdjustBrightness(BrightnessSlider.value);
PlayerPres.SetFloat("myslidervalue", slider value)
PlayerPrefs.Save;
}
uh
BrightnessSlider.value
also dont copy myslidervalue lol
its an example
name it something smarter
like BrightnessSliderValue
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
@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"
error code means nothing alone, you have the show the exact error and which line
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
what is PlayerPrefs.Save; supposed to be?
I have to put "public static void Save();"
put it at the start?
lol
how do you call a method/function in C#?
note that every other line of code in your example is calling one
correctly
except that last one
()?
no cheating 

thx tho
np i was insecure of the answer tho lmao
if someone can help me out with this one i would be grateful, cant really seem to make it work
thanks in advance ;w;
!code
Posting code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
void Start()
{
brightness.TryGetSettings(out exposure);
AdjustBrightness(BrightnessSlider.value);
PlayerPrefs.SetFloat("BrightnessSliderValue", BrightnessSlider.value);
PlayerPrefs.Save(AdjustBrightness);
}
I think this is it
its not
not long, I think 3 years
doesnt work
ofc it doesnt
💀
I ave to load it right?
thats usually how saving works..
you also need to trigger an event to load on scene changes
luckily unity has one built in
lets make a thread tho, we're flooding the chat. should've done it sooner @alpine mortar
Freddy thread
^ 🥺
box or capsule collider for better detection if rigidbody is groundded?
I would not use colliders for that
something like Physics cast
or overlap
im not using it to directly detect. its just that there was an issue raycasting down for a box collider when my character was standing on a slope.
the program thought my character wasnt grounded
sounds like an issue with your raycast, not the collider
Physics.Raycast(rigidbody.transform.position, Vector3.down, collider.bounds.extents.y + 0.1f);
this is the code I used. works perfectly on smooth surfaces, but not on slopes
Is it 2d or 3d
3d
the best thing to do when in doubt is to debug your raycasts(adding visual debugs) to make sure they are where we think they are
right because collider.bounds.extents.y + 0.1f will not necessarily reach the ground then
you probably should use a BoxCast instead of a Raycast if your collider is box shaped
why didnt i think of that? I'll give it a shot
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?
Probably via the editor API, but you cant include that in the build.
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
Okay, thx
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
show any relevant code
if (collision.CompareTag("BlacksmithTeleporter") && Input.GetKey(KeyCode.E))
{
SceneManager.LoadScene(2);
transform.position = new Vector2(1.994f, -1.569f);
}
this code does not seem related to your camera's positioning
oh my bad. im using cinemachine and it just follows the player
why is the orthographic size so small?
yeah thats hella zoomed out
smaller would be zoomed in, no?
oh yeah ur right mb
which makes this even weirder. are their objects just incredibly tiny?
super tiny lol
i bet they are using like 16x16 or 32x32 sprites and just left the PPU at 100
@elfin eagle do you change the ortho size anywhere ? or maybe switch cam
im using 16x16 sprites
but what is PPU size
then change the pixels per unit size on the sprite importer to be 16 instead of 100
ohh ok that worked thanks. for some reason it was changed
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
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
how bad is this for a monobehaviour constructor?
well considering unity won't be calling it, i'd say it's 100% pointless
Monobehaviours can't have a constructor
yea just a getaway
or do you mean this is supposed to act like a ctor since it isn't actually one?
to instantiate a new one and plug what you do like how you would with a ctor
yes
i'd personally return the instance after doing all that, but there's nothing inherently bad about it
ah yea returning it can be a good addition
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
there are beginner c# courses pinned in this channel
the way variables work has not changed since before you were born
lol
even though brackys is not exactly a good place to learn c#
Ahter
Brackeys is terrible and causes a LOT of bad habits in newer coders.
it's hater for me, so you all are wrong
Wrogn lol
internet has always been messing with emoji spam ever since
anyways
best way to learn c# is from docs itself
painnnn
there's a LOOOT examples and detailed to core
yea, have to practice tolerance though
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
yeah even some simple C# function microsoft goes way too overcomplicated with example
which channel is the tutorial on?
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 😭
channel 2
hey I was almost right
was gonna suggest you check new cams if you followed up on it with a reply 🙂 at least its sorted tho
no yeah i changed the orotographic view that fixed it
but like doing this is much more convienet
neat, didnt knew we have c# tuts on pins
my game uses 3d models but completely ignores the z axis. should i use 2d components?
no
aight
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?
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
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..?
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); } }
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
man you should start using interfaces
IDestructable or something
where is anything thats supposed to delay anything?

is something simple,i used the OnDestroy method to the script attached to the fire particle to access to the parent component that make it explodes
not really sure what is supposed to happening?
and obviously i added a delay of delete the fire with the setOnFire method
what do you need to do
copying the gmod barrels behaviour like another times
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
I have no idea where these methods are, u have to share whole script
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
}
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
ty
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?
The inspector shows a rotation that expresses that orientation
There are literally infinitely many
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.
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
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
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?
You shouldn't touch the solution/projects when working with unity. They are generated by unity automatically and even if you make changes, they would probably not be reflected in the unity project.
when i access dictionary["something"] does it both create new entry if this doesnt exist and overwrites existing one?
if you're accessing it, then you're attempting to retrieve the value based on the supplied key . . .
you can't create/add a new entry unless you write to it . . .
yes write
Accessing a non existing key would throw an error
strange i tested and it not errors
Regardless of whether you're reading or writing.
dictionary["thing"] = "abc"
when using dict[key], this will overwrite the existing value or create a new value with the key . . .
cool it will make code much cleaner
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 . . .
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 . . .
How do I add reference? (mysql)
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
And is the DLL in a Plugins folder and functioning properly?
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
You have to include every assembly it requires until all the dependencies are satisfied
ive only found one on google but its from 7 years ago. Not sure where to get the dependencies
because im not storing it locally
huh you're putting a remote db with dll ?
ive written the php and can read data from the sql table but unity wont let me write the data without the imports
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
What? There's no reason to need a MySQL lib in Unity if it's your PHP web app doing the actual interaction with the SQL database
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 😱😱
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.
I said its on a php file
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.
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
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.
"I do"
You do have a server?
I do
I though the "I do" was answering the "unless you mean something else".😅
Then you access your db on the server.
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 😞
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.
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
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.
yea. i mean if its faster
Nevermind that anyone walking by can press the button.
anyone have experience with convex mesh colliders with Rigidbodies attached to them causing some weird issues?
What issues?
i am facing issue with coin reset
it doesnt go back to 0
after run is over
this is my coin script
because its static
how to fix that?
make it not static or explicitly set it to 0
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?
that produce lot of errors
xD
what other scripts reference this class?
and why is it static in the first place?
probably because they don't know how to properly pass variables with references
A change like that requires refactoring.
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
how do you pass variables properly?
i would probably just do something dumb like CollactableControl.coinCount = 0 or something
what is the error you are getting?
yes so make a reference
i have script named
otherscript
and reference to collectablecontrol script
still it shows error
when you make a reference to the script you have to access the methods/variables through the reference
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?
- Get a reference to your collider
- modify whatever "size" property you want to modify. For example for a SphereCollider that would be the radius
public float range = 10f;
public SphereCollider detectionZone;
void Start()
{
detectionZone = GetComponent<SphereCollider>();
detectionZone.radius = range;
InvokeRepeating("UpdateTarget", 0f, 0.5f);
}
like that?
When you say a reference to CollectableControl, how do you do that? It's more than just making a variable for it.
You may wanna check out this link
https://unity.huh.how/programming/references
sure except there's no reason in this example for detectionZone to be a member variable.
or alternatively there's no reason to use GetComponent it it's a public member variable since you can assign it in the inspector
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
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
thats what im confused by. doesn't GetComponent grab and return the item from the prefab?
this
as in assigning the size?
no assigning the reference
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;
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
Wdym by "directly via the gameObject"
i think im just getting tripped up by how gameobjects and their components work
do i need to use GetComponent to modify the collider from within the script
You need a reference to the collider to modify it in the script. GetComponent is one way to get a reference to the collider
Saving the reference in a variable means you don't have to call GetComponent repeatedly which is both ugly and bad for performance
its resetting now
but at end of my run is over panel it shows 0 coins
nvm fixed thanks guys @rich adder @frozen mantle
https://gdl.space/ziqocobure.cs
why does the "instantiated.GO" still hold the reference to the prefab and not the gameobject I actually instantiated?
at no point does it reference a prefab
the _product.GO is a prefab
okay, but yet you do not pass the Product instance a reference to a prefab anywhere in the code you've shown
I know and thats what´s confusing me
how do you know the instance you created references a prefab?
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
then you're looking at the wrong instance of the Product struct
I am pretty sure I am not
and i'm pretty sure you're wrong
show the relevant code where you are actually experiencing this behavior
Ive found the issue, it is the line 11 in the snippet I sent
there it is adding the product instance with the prefab as reference to the list I am looping through
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.
Well there you go. Now you know that it wasn't the Product instance you were creating and storing in your instantiated local variable that was the issue
how to deselect inputfield when character is mvoing?
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
probably you didn't actually follow the tutorial exactly!
make sure you made IInteractable an interface and not a class
I follow everything.
I think interface is a reserved keywork. 
Ur trying to make interface a method name?
Also interface type is coloured green, that's probably Visual Studio Code.
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
do you have intellisense working? that should be an error
i dont have that
Use Visual Studio instead of VS Code (if you are) check #854851968446365696
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
mate just save yourself the headache and install Visual Studio instead
ok
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
im going to swap since i dont really have time to fix vs code
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?
Could someone help me with the Q I asked yd? #💻┃code-beginner message
@keen dew lol this does not help
How far did you get in that troubleshooting page?
@verbal dome I'm still looking through it but it's not helping
It covers 99% of issues when it comes to this
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?
i had the collider above it and it wasnt working. switched it and now it works...
no, i mean above it on inspector
Inspector order dont matter
you are aware that you are the only one seeing your problem, are you?
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?
show the inspector for both of the objects and any relevant code
How can I change the speed of this animator "node" through code?
if you leave Speed at 1 you can set a parameter for a multiplier and just change that parameter
Thank you it works fine
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?
Why doesn't the parameter update live in the Animator window?
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
probably because you havent selected the animator on the gameobject
owner.animator.SetFloat("MoveParam", owner.unitData.moveAnimMultiplier);
Debug.Log("Animator moveparam: " + owner.animator.GetFloat("MoveParam"));
The debug.log shows "0"
owner.unitData.moveAnimMultiplier is not 0
are you certain you are calling SetFloat on the correct Animator instance?
and that nothing else is assigning to it?
nothing else, im not modyfing the value anywhere else
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
okay wait
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?
i think i might have referenced the prefab
at a guess i'd say you have a reference to the wrng object somewhere
instead the Unit in hierarchy
yeah that'll do it
the current state of your input action's Vector2 value will be stored in the moveInput variable
got that but am i right about the first line?
void OnMove(InputValue value)
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.
thats not what im asking... im trying to get my head around how functions work...
you asked about value for the InputValue
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".
there are beginner c# courses pinned in this channel. you should start there if you do not understand how methods work
yes or no would have been more helpfull.....
it gets stored in InputValue . value is just the name of the object you're accessing..
it can be named joe for all it matters, the value is the same
should def do some beginner c# courses though
then the next line would be
moveInput = Joe.Get<Vector2>();
?
thats all i wanetd to know... phew....
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
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
yeah one problem at a time haha
raycast takes a direction not position
ah got it working thanks 🙂
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?
Could get all potential objects, then do a dot product on vector2s
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?
@teal viper Cool, thanks, will take a look 🙂
Seems to be more common to deal damage from the objects that are doing the damage dealing.
Personally, I would have a variable on the enemy with how much damage they cause, and when you collide you grab that variable and adjust your health accordingly (health script on player).
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?
You need to manually listen for the escape button and reverse the state changes you made in your code
is there a line of code where i can just "unlock" it?
Its basically the same you already did, just another CursorLockMode and visible needs to be true again
ah okay thank you
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?
Any Texture2D created by your code will be read-write enabled, by default
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.
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?
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
got it !
oh this dummy have a othe question!
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
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
you used the wrong conversion factor
Mathf.Atan2 returns radians
you used Mathf.Deg2Rad
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
·····················...
so that made the resulting angle even tinier, since Deg2Rad is going to be 2 * pi / 360
Also why is direction made of the horizontal input and gravity?
that should be separated, yes
Also x and z are reversed in the atan2
my noob idiot brain did that
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
i should report this toturial .
so many wrong doings in it!
well that wasnt in the code he wrote untill where i need it 😁😁😅😅😅😅😅
dummy me!!!!!!!!!!
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.
@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#.
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? (:
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
my settings in unity and the 2 scripts seperated by a big line in the pastebin for info
"what is ground" -> "nothing", maybe ?
and "FixedUPdate"
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
it's probably the FixedUPdate, c# is case sensitive so FixedUPdate won't be called
doesn't complain about duplicated method
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
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)
and silly question but the wall has a collider yeah?
yes, and the ground too
it detects none of them
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
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
hmm won't be that then
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
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?
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){}
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
Normally the assemblies take the name of the tool being developed. If you want to add you name to something look at the assembly info file
Do you want like a deadzone? Like what is your understanding of more controllable
yes, something like that
Basically i moved all my scripts to another folder and now its says this ☃️
You can check if the Mathf.Abs of your roll is smaller than e.g. 0.3f (30% deadzone)
you have duplicate scripts
Ohhh
Thank you :>
how would you do that in a script
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.
Input.touch is only for mobile users right? Is there one where i can use for both pc and mobile users?
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?
Im sorry, but if thats trouble for you, your first stop should be a c# tutorial
if (Mathf.Abs(roll) < 0.3f) return;
Editor folder is exclusive to Editor Only scripts
... yes? I'm talking about using them in-editor.
Input.GetMouseButton(0) is emulated on touch
(Turn Input.simulateMouseWithTouches to true to be sure)
Are you trying to load them on gameobjects in your game?
yeah im trying to get drag
oh wait yeah thank you
On a UI element?
no just in general
and then use line renderer to show outlines where u dragged
Alright, if you want drag look at IDragHandler, IBeginDragHandler and IEndDragHandler
they give you an easy way of handling drag
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.
thank you
Scripts in the "Editor" folders are not supposed to be attached to gameobjects. They should do stuff like creating editor windows
{
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 ?
Wait, really?
Weird design.
Guess I'm just gonna spam #if UNITY_EDITOR then.
Thanks for the answer.
The Editor folder should be for editor scripts. If they ever need to come out of the editor folder that's a problem
What are you trying to achieve with your scripts? Maybe you can either remove the editor-only lines or skip the gameobject stuff
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.
You should have a look at custom editor windows then, you dont need those scripts on any gameobject
If you already have Odin installed - even easier
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).
Do you have Odin by any chance? If so its fairly easy
Never heard of it. Will check it.
Guess I will stay with my solution then, but thanks for the suggestion.
Even then you might want to create a custom window, even without odin its not that bad to create one
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
does anyone know how to reference a specific object within a hashset?
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
!learn, and probably learn c# from the most basic (console.writeline("hello world")
:teacher: Unity Learn
Over 750 hours of free live and on-demand learning content for all levels of experience!
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.
yea its interesting when doing courses and such I can understand what they doing and reading other people's code I can help them troubleshoot whats going on but when trying to write something myself i just go blank no idea why
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
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
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
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
thanks for the tip
like if(gameobject != null) ??
What line of code throws this error?
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?
in the canvas
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
Create multiple "parent" canvases,
- Background
- Base layer
- Foreground
- Always on Top
And add your UI element in the layer you want it to show
not sure if there is a better way
so any clue?
If you destroy the specialEffect and then try to invoke it that error would be the result
well the problem is that they are in the same script
https://img.sidia.net/ZEyI5/NedUSALU87.png/raw
Then i tell the UserInterfaceView to please parent the UI i want to create in the layer I chose, that way the important things are always on top if put in the popup layer
the second method
is the special effect
how do I check if the object is destroyed
or gets destriyed
{
transform.position += Vector3.down * Time.deltaTime * fallSpeed;
}```
is this considered teleporting or is the object moving properly?
Teleporting
damn
well u are basically tping ur character down but very slightly repeatadly so it may seem moving but it is actually tping
If you want to emulate physics movement, add a rigidbody and either use MovePosition or AddForce on that
if (gameObject != null)
exactly if u want to do by changing the transform use MovePosition or Lerp
ok thank you
its not that i want to emulate physics, i just want the collider to interact properly with the istrigger
collider = physics
thats not what I mean
use Vector3.MovePosition?
The Physics System is what resolves the interaction between the collider and the trigger
im wondering if an object enters a collider, teleports further inside the collider, does it mess up the ontriggerstay method?
yah and to trigger something one of the objects must have a rigidbody
So yeah, add a Rigidbody and use the Rigidbody.MovePosition
it already has a rb
Then reference it in script and move it via that
exactly
alright
i were downloading unity then it stucked here
i got notification from antivirus that said it been blocked
how do i unblock it
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
that didnt work
I still get the error
hmm maybe its something else
Click on the error log twice and it will lead you to code where it causes the error
is it possible to call a function/method from one scene then define it in anotrher scene
methods are defined on classes, not on scenes
scenes are not a concept in C#
yea but in another class in anotehr scene
you can indeed get references to objects in other scenes and call functions on them, no problem
ok
what is the difference between - and -=
- is the subtraction operator
-= is a combined "subtract and assign" operator.
x -= y; is equivalent to:
x = x - y;
ahhh
thank you so much
that makes so much more sense than the drivel i've been reading
here is an example usage so you can understand better 1.someFloat -= 1; 2. someFloat = someFloat - 1;
these both will do the same thing
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)
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.
that is able to be both read and written to by other scripts
static modifier
could you elaborate please?
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
you can use tags or layers to make that collider ignore your player
how to i do that as i haev a function but it doesnt recognise it on the other scene
Yea, it's set to ignore the player already because I wanted the enemy to be able to pass through if it kept coming after triggering a knock back
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?
@wintry quarry
GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
wdym by "it doesn't recognise it on the other scene"? Show in detail what you are trying to do and how you are trying to do it and what's gping wrong.
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
When you say "static class" I don't think that means what you think it does. There's a difference between "static class" and "static variable in a class"
so i made a function and all that but this is what happens when i call it (on dif scene btw)
to access a static variable in a class you do ClassName.VariableName
functions don't go on scenes
functions go on classes
you need a reference to an instance of a class to call a function
so someReference.DeathScreenFunc();
what is the reference,
Just a normal C# reference of your class type
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
Yep, this is literally Unity 101 "referencing scripts" stuff
do some basic tutorials
ik how to reference scripts but i didnt know if u had to reference scene or smth
To do it between scenes you may need some techniques like Singleton or dependency injection or FindWithTag but that's not a huge hurdle
well then say it instead of setting me up for error
Are you trying to reference a script on a game object in a dfferent scene?
I'm not setting you up for error - I'm hammering the basic concepts into your brain
learning requires error
trial and error
It's a process
ima ask chat gpt as it has manners and is actually smart
lol
and answers to what i asked
Holy moly
and listens to what i said
They did tell you that. Reference the instance across scenes and use that
We did listen. what you said doesn't make sense
currently having this issue with the red OnTrigger colliders at the bottom. sometimes they register the object colliding and destroy it, other times they dont. I have no clue why.
You just don't know what "reference" means because you've skipped the basics
this is u 10 seconds ago "Are you trying to reference a script on a game object in a dfferent scene?
"
if anyone has any tips i'll gladly take them
you'd have to show your code and your object setup
sure
Also do some debugging steps
Well, are you
i do know what i means,
i alr said
"how do I reference a function in another scene" was your question. That does not make sens
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);
}
}```
Okay, then what is the problem? Reference the object you want and call the function on it
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
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;
}
}```
Input;.GetKeyDown inside OnTriggerStay is your problem
you cannot do input handling in physics callbacks
physics don't run every frame
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();
}
}```
AHHHHH
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
i was trying to do that with HashSet but i didn't get how
yeah HashSet is actually better
but didn't want to confuse you
you can just replace List with HashSet in my example and it will work fine
yeah that makes sense now, I also didn't know that physics didn't run every frame so I had no idea why it wasn't working
oh so if I declare a variable as static in a non-static class, is that what they meant?
Is Unity moving to .net core anytime soon?
I don't know who "they" are or what they said.. Maybe?
ah fun
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.
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)
it usually works for me, also they were being very condescending saying "go back toi begginer tutorials" and stuff when i have seen them be wrong before too. They seemed more focused in annoying me than listenign and trying to help
Saying go back to beginner tutorials is objectively not condescending. You are very much a beginner and it is good to refresh yourself periodically.
Gpt will harm you. It SEEMS like it works, but I promise it gives you only superficially good answers.
You were rude to their responses
you will get one OnTriggerEnter call per collider pair. They will happen sequentially in no defined order
they said do u know what a reference is, when i was 7 years old i knew that
No. You did not. Not in a programming sense. But I see you just want pity and not help. I will give you neither and instead block you. Good luck. I recommend you get a check on your ego before coming back
Holy moly dude. He said reference it and you asked "What is the reference then"
yes, what is THE reference for that thing not what reference means
im reading your example here but im confused on how I can reference note in the method that is being called further down?
You needed to create the reference! Lol, so obviously you didn't know what you were talking about
neither did the other person
wdym by "note"
note is just a local variable inside that one for loop
it is not used nor needed to be used anywhere else
oh ok
i was just confused
i thought you were using it in another method outside the loop
nope
Oh yes - i'm passing that to a function
i guess if i declared it separately
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
wait why does it say score twice
you wrote that code not me lol
shit that's supposed to be combo not score
you should probably make a public function like AddScore instead of manually modifying another class's static instance variables
inside AddScore you can increment the score and the combo
yeah I was planning on doing that since the combo was gonna affect the score, its very rough and unclean because i was pulling my hair out trying to figure out why it isn't working
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
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 ?
i think you mean method not void
which method it is?
it's "method" or "function", not "void".
Void just means the method doesn't return anything.
As for your question you have to be way more specific because Unity has lots of checkboxes for lots of different things.
oh ok
because if i not put void that return anything?
and i talking about the toogle checkbox
show a screenshot of which checkbox you mean?
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?
the ui element check box
I think you need this one instead
https://docs.unity3d.com/ScriptReference/NetworkReachability.ReachableViaLocalAreaNetwork.html
the doc says
Note: Do not use this property to determine the actual connectivity. For example, the device can be connected to a hot spot, but not have the actual route to the network.
https://docs.unity3d.com/ScriptReference/Application-internetReachability.html
ok so instead of using a find methode that is apparently cursed will it be better to use "public static float"
those are two totally separate concepts unrelated to the dicussion
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/access-modifiers
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override
no not at all. Static variables are not a good quick fix
we already mentioned you should only get it once, and cache the reference ( Store it inside a variable )
can an object not be destroyed by OnTriggerExit?
they can
thats weird
why not
this is meant to destroy the object if it leaves the collider, but it doesn't
{
notesInside.Remove(other);
Destroy(other);
notesReady = false;
SubtractScore();
}```
that's destroying the collider
not the GameObject
i also did other.gameobject and it didn't work
How do you know it didn't work?
Did the code run?
are u certain the function is working ?
protected override void OnEnable() why that make me a error?
because there is nothing to override
you'd have to say what the error is and where you put it
oh override is for a already exsting method ?
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
i see that on the doc xd
which doc
why are you looking at that
public class A : MonoBehaviour
{
protected virtual void OnEnable()
{
}
}
public class B: A
{
protected override void OnEnable()
{
}
}```
idk
I linked you to the isOn property:
https://docs.unity3d.com/Packages/com.unity.ugui@2.0/api/UnityEngine.UI.Toggle.html#UnityEngine_UI_Toggle_isOn
ignore the rest
wait so what does it need to use 
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;
I never used those methods , not 100% on it. I can test it if you like. I usually just make a webrequest and if it fails then there is no internet.. Thats prob not the best but it worked for me
you mean something like this:
UnityWebRequest www = UnityWebRequest.Get("http://www.google.com");
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.Success)
yea kinda something like that
ye what confuses me it works like a charm in editor but not in build
seems like others had the same issue 🤷♂️
few people mentioned doing what I did with the webrequest
ngl annoying xd
but how i can use it for make anything when she are on?
ok i can define him if he are on or off but how i can use that after?
For some reason the 2nd one gets disabled but the first one doesnt get anabled, if anyone can help and needs extra info lmk
Sorry I don't understand your question. Use an if statement is that what you're asking?
unity editor bug
what happens if you set a variable to public but also serialise it?
nothing
public variables are already serialized
oh ok
There are two ways to make a field serialized:
- make it
public - mark it with
[SerializeField]
that makes sense
doing both won't make it "double" serialized or something
yeah i figured, just wanted to know if it was doing something secret i didn't know about
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
.
from the screenshot alone we can't tell anything
also check console for runtime errors?
show complete script
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
I dont think fullscreen would work in editor build
ok ty
so i need to build the game
ok x)
Does yield return www.SendWebRequest(); pause if someone elses game build in the world is sending a request to the same url?
can a unity event not have a vector2 parameter?
iirc UnityEvent should support any types regular c# do
this doesnt appear in unity events
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;
Hmm yeah not sure, I don't use the inspector for events 😛
I prefer Action and do everything in code
hm alr ty u anyways
I'll ask in unity tlk
talk
are you talking about multiplayer ?
yea. my host generates a port and my game needs to read it
so I figure send it through web request or sql
but what if more than one lobby is made at the same time, right?
everyone is running their own copy of the same game, they shouldn't affect eachother
the web request is sending it to the same url tho
so? websites servers deal with traffic on the same address
game -> web host file -> server, port generated -> web host -> game
saved to a pre existing text file ig
i mean yeah if you trust anyone can connect without validations in place..
wouldnt matter. all it shows is a randomly generated port number
oh just the port ? ok
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
hmmm
you could always test it n see
would only happen during heavy traffic
cant test it
unless I am able to read the file first and make sure its value is "empty"
what if one person has slower internet / loses connection, does your server handle that?
just wouldnt want a bunch of ppl waiting for other peoples request to finish
hm?
just make them different async Tasks or separate coroutines no ?
that should create a task for each user
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
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
this prob should go in #archived-networking
when the port reaches 0 players it closes the application and opens a new one so it generates a new port/host on the main thread
danggg here i am , just letting something like relay / lobby handle all this.
I am using relay, with steam matchmaking
oh Unity relay ?
custom
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
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
cost $?
I do tho
