#💻┃code-beginner
1 messages · Page 476 of 1
you are the one who insisted that the documentation was wrong even though it was really your code that was wrong
even though the error message was very, very clear
I am trying to program Acceleration into my 2D rigid body but when I play test it, the max Velocity of my RigidBody is always 1 or -1
https://pastebin.com/firbyJy4
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.
I think this has something to do with it being in update rather than fixed update and/or something about it not being executed gradually over time
speed = Mathf.Lerp(player.velocity.x, topspeed, rate);
this line is pointless because you are assigning to the local variable named speed which you never use after this line
or rather, you never use it for anything other than displaying it
also for future reference, when using a site like pastebin where there's no syntax highlighting by default, please have the courtesy of selecting the correct language so that there is syntax highlighting
ok
Always use FixedUpdate for physics. Update is for graphics and is framerate dependent, and FixedUpdate runs separately at fixed intervals. Otherwise increasing FPS would increase acceleration, for example
so your suggesting that its because it IS in Update rather than fixed update?
I'm looking at your code now, but I can say with certainty you should move the physics stuff to FixedUpdate. Also see this article by Unity themselves: https://learn.unity.com/tutorial/update-and-fixedupdate
Also, I would recommend using clearer names. Calling your Rigidbody2D "player" is somewhat confusing, as often the player is the entire GameObject, not just the Rigidbody2D.
However, even in Update, setting a velocity to a Rigidbody2D should make it accelerate. Can you see what speed & player.velocity are by logging it to the console or something? My first guess would be that something is going wrong with them
But I have to say, you have a lot of things that do nothing in your code (two separate speed variables, random variables that do nothing, etc.). Maybe look up & follow a tutorial first so you get an explanation of what everything does
i got the PlateCompleteVisual Script here to deactivate the items but it activates it in the game.
I want the plate to be empty when it spawns and i interact with it but some of the items are there when i interact with it when it should be empty.
this is the script that goes with the plate
guys quick question, what's the "Editor Loop"?
Everything related to updating the Editor itself. Running editor scripts, keeping the Hierarchy and Inspector windows up to date as the game runs, etc. Won't be there in a built standalone executable so this entire section can be ignored when profiling
it literally takes more than half of my game's performance
that is a good thing
Playing in maximized will ease off the performance hit, as it needs to visually update less Editor things
This means I had no problems with optimization after all, but I'll still try to change my particle simulator with the VFX graph to see if there's an improvement when I figure out how to do that
make a build, try your game for real
I would but at this stage I can't really do that as I'd get INFINITE errors so it will have to wait
well maybe that is why the editor loop is taking up so many resources
basically only 1 scene works atm, and I need to fix the rest for when I build the game as rn I'm testing stuff
when using tuples in c# like (int,int) is it by default the value tuple type or the class type ?
hovering over it does not tell me if its a struct or class
Exception catching and stacktrace unwinding is pretty expensive as well, so fixing them will be a bonus
It'll use ValueTuple the struct, verify by logging its type: Debug.Log((4, 3).GetType()), should output System.ValueTuple``2
good to know
ok 18% of my resources were going to particle simulators
ty
any good way of activating and deactivating a boolean that is in a raycast that activates only once?
You can't activate a bool. It's either true or false . . .
thats activating it and deactivating it, literally by setting it true or false
anywho, any good ways of setting a boolean true or false that is in a raycast that activates only once?
No, that's a different meaning altogether. I was trying to figure out what you want to do . . .
Are you saying the raycast activates only once or the bool? This is why it's confusing . . .
boolean that is in a raycast that activates only once?
the raycast only activates once
Uhh, how does the raycast activate once?
Wait, do you mean the method is called only once . . .
it only activates when Getkeydown is true and when it is done getting invoked
let me get you the script
Do you mean the Raycast method is called?
called only once, yes
i made it to do that
https://gdl.space/nodilavepa.cs only look at the raycasthit1 for now, raycasthit2 is broken for now
The bool in the raycast. Can you explain that part? I checked the Raycast method(s) real quick and didn't see any bool parameters . . .
Warning line 105: hit1 will be assigned a new value even if the raycast did not hit anything!
yeah
This is because when using an out parameter, it must be assigned a value inside the method before any return is reached
i get that, i had it as hit2 before but as i said its broken for now
will fix it when the raycast1 is fixed
My player won't move to my keypress all of a sudden. It was working before but it stopped now.
I haven't changed anything in the scripts and a new script I made was for something different.
!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.
check console for errors maybe its pausing the game
The console is showing no errors
Nobody can help without seeing some code
fixed my issue roughly using coroutines, still thank you SPR2 and RandomUnityInvader(); I appreciate it 😁
can you share boths scripts? share it according to the bot msg here
#💻┃code-beginner message
Player Manager: https://gdl.space/acifimugon.cs
Player Movement: https://gdl.space/badufapupa.cs
Player Input: https://gdl.space/nowawayuye.cs
i dont see InputEnabled = true anywhere
I do
ohh wops i had a whitespace in my search 😅
Check what code is running with the debugger or logging
and make sure errors are not disabled in the Console window
is your playermanager script actually getting your input script?
playerInput = GetComponent<PlayerInput>();
This is what the debug looks like for the player
have to put logs in the script make sure they run
Debug mode is not the debugger to be clear
it half debugs, not even. put some logs in your scripts like nav said
afaik all it does is show private variables in the script.
How would I do that?
Debug.log();
At the end of the code right?
wdym "the end of the code"
when in doubt, put it in update
guys i made a pick up tool script and everything works but the only problem is that if i press e at any location it will pick it up how do i make it so that if we press e when we're near the object it'll pick it up instead if being at the other side of the map
use physics queries, detect the colliders
ty
Seems that it isn't picking up where the player is when it starts
Im confused as for something
Why would one even need to have ANY Variables Private when there are abilities that can make ANY of them public
because you dont want other scripts changing the value of a variable when it shouldn't
see (encapsulation) https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/tutorials/oop
I got this problem with the plate where the visuals are activating when i pickup the plate when it should be empty. This is the PlateCompleteVisual Script: https://paste.ofcode.org/?edit=AX5R5VBLmLNutmimjyUxDJ and this is the PlateKitchenObject Script: https://paste.ofcode.org/?edit=35dr7vuQwJHGAyuUhMNLhT3
Not sure what I have to do to fix this. If anyone could help it would be nice. Thanks
If u went that far in the project, you'd probably have an idea, but try to check if your plate prefab that you create(on pickup) doesn't have the image on the plate.
OR debug the code "on plate pickup" or w/e the function is.
it seems that the deactivation and activation is working but the visuals wont show up. it might be a rendering problem which i also dont know how to fix.
If u look at the script which "activates visual", see if it actually does anything, since you are following a tutorial maybe this part wasn't implemented yet?
@static wasp the variable you change on the unity is different from the variable you enter in the code
the variable in the code is like a start point
oh ok, thx
then you can just tweak around it
Hey guys.. if I create an UI button.. to find the method here as shown in the SS I always need to create the method as public? no way to create it as private and acces it here some how?
Nope
hmm. ok thank you.
if the funcions I have.. as public.. they are inside my UIManager script. I need to drag the UIManager script here correct?
I cant find the functions doing that way. what am I doing wrong?
example of one of the funcions:
Are you dragging in an instance of the script?
Well, the script itself is just a script asset
It doesn't represent the class that's inside of it.
I dragged the object now UIManager and worked
curious, why is "InGame" added to the variable names? do you have buttons "OutOfGame"? wouldn't it be _dmgSkillButton?
I thought weird that no one asked it.. hahaha I was sure someone would
I am trying to find a better name for it.. but I will have a dmgbutton while the game is running or in the menu of the game when you die after it
so INGAME its while you are playing.. and not in the menu itself
hahahahaha
I am very bad with variables names
I try my best.
i'm a bit OCD about stuff like that . . .
how do you add a menu item to this menu. its the one that shows up when you right click a scene in the heirarchy
and trust me I just dont name them I take some minutes to think
they don't have to be different names unless they're in the same script . . .
They will be in the same script
oh, that's . . . different . . . 😅
inside the UIManager basically
Actually now thinking .. I can have more scripts inside my UImanager object. right? maybe I should create 2 scripts
one for buttons inside the game while running and one for when its in the menu
then you can do _dmgSkillMenuButton . . .
oh, i would not have thought they were in the same script . . .
you would not have 2 scripts inside UIManager object you mean?
i would have a different script for the in-game buttons than i would for the menu buttons . . .
yeah that is great idea I will do that
With that I can have better variable names and I dont need to name them with Ingame etc
the in-game buttons seem tied to gameplay and don't have anything to do with a menu . . .
With inherited classes, is there any way to have these show up properly in visual studio? They work but none of VS's reference stuff works with them.
https://i.gyazo.com/cd8e9c4d63a7584bdb229ef0e2aebdee.png
what is supposed to show up?
all of the methods? the members from ani? the members from col? it's hard to tell which/what you are asking about . . .
states() is a local method, and is yellow.
The other methods are from other scripts or the class it is inheriting from, and they show up as white.
When mousing over the states() method, it shows its location and other info.
Main thing is I just want to be able to visually see the methods easier rather than in white.
make sure your !ide is configured with unity . . .
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Thanks, thats all it was. Just forgot to since I hadn't installed Unity in a while and was opening an old project.
np, it happens a lot . . . 👍
i need help,
when i try to build my project i get this error (Assets\NavMeshComponents\Scripts\CollectTilemapSourcesCache2d.cs(30,68): error CS0426: The type name 'SyncTile' does not exist in the type 'Tilemap')
can you show that script
someone help, my collisions arent working
void OnCollisionStay(Collision collision)
{
if ((Physics.Raycast(transform.position, Vector2.down, out hit, 1.05f ) == true) && is_grounded == false)
{
is_grounded = true;
}
else
{
is_grounded = false;
}
print(is_grounded);
}
nothing is being printed
Lerp Movement + Input
Same goes for your Physics query, it's 3D not 2D
!docs look at the API docs for that method and make sure you use it properly
help the ai i coded (without ml agents ) wont stand up properly i let it train for hours, and the problem seems to be with the old neural network
https://paste.ofcode.org/hKy3L3WgxNzuX6AsK6xabJ
someone please help me ive been trying to figure out why it wont work for 24 hours 😢
i just want to sleep😭 i told my self oh ya its a quick fix ill sleep when its fixed, but it i never got it fixed, so please please help me
Try to turn on “is trigger” on your collider
that makes me fall through the floor
Oh ye mb
Were you able to find an answer?
i fixed it tho
is there a way to increase the gravity of an object?
like i want the object to fall fast
hey, when I tried to acsess the player by this line of code I got this error, I think its because the player is a prefab and not a game object, so is there another way to acsess a prefab or this is the way but my code is wrong?
do you have a gameobject called Player when this line of code runs?
and does it have the Unit component
it does have a unit componetn
but its a prefab
does a prefab counts as a game object?
no, it needs to be in the scene
unless its a prefab IN the scene
which that works too
im just thinking maybe you cant run this code on a ScriptableObject to find the gameobject, not sure
I just had a qestion
Is there a way I can put this
resolution that i use in the editor which is 800 x 600
to the build
so I can have the pixelated look ?
in project settings i think? and build settings? but #💻┃unity-talk is a better channel
its a static method, with no knowledge of where the code is being ran from.
you should debug what is specifically null, theres 2 things on that line that can be.
you can split it up
id honestly change this whole code up though. pass in a reference to the Unit when calling this method and now suddenly you have items that work with any character, its more performant, and wont be completely fragile.
I fixed it, the problem was when I loaded the prefab into the scene it loaded as "Player(Clone)" instead of Player
so I had to change it in the code
another reason why you shouldnt use .Find
I guess so
unrelated, but, it is better to not name things names like Player, Camera, Collision, collider, etc. because it might cause a problem
you could name it names like player, camera, player_collision, etc. so unity doesn't get confused
allright thank you for the tip
wat, that is not true
that only applies to if you're naming a class. they were naming a game object
i once made a variable called Collision, which made unity be annoying
even then, they dont have a variable named player.
that tip doesnt apply to what you're doing at all. the name of the game objects can be whatever you want. unity does not search by name for it to matter
like this situation
it's just a tip
i feel you're confused on what a variable or class name is, in relation to them having a string.
and the tip gave them now misinformation
i have a question is verry hard for me to resolve it my player don't take any damage i give more information in vocal
well mb ig
Add some debug logs to your code to see if it executes.
no he don't work i think is the collison ?
Make sure the player collider is set up properly . . .
If you press 'H', does the player take damage?
yes
Then check that the player and enemy colliders are set up correctly . . .
Share the updated code with the debug logs.
i found in my component i use boxcollider and not boxcollider2D.....
Just to follow up on this. I've put up a video of my random room generator
https://youtu.be/WDmrc6Spw7k
If you are interested in learning more feel free to DM me
Random room generation with procedural placement of room contents
Made with Unity - Work in progress
In void Shoot it gives me error
please use a paste site to post !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.
Thank you so much!!
Is it 3d?
yes
looking at this firePoint must be null
Hello, I am making this game in which these red squares will follow around the white triangle (player)
here is what I'm using for the enemy follow script
I want to create a prefab of the enemy, but if I bring the prefab in, I have to manually assign the reference of the player to every prefab
any way I can directly reference the player in the code?
normally you would assign that at the point you instantiate your enemy or you could have a singleton which holds the reference to the player
also please do not post screenshots of code
sorry
it's empty game object, child of gun
that is irrelevant, the problem is you have not set a reference to it in the inspector of the gameobject using this script
im using fusion 2, both player and bullet is prefab, but the gun is not, it is only child of player
i will send a video
no. Again irrelevant, read what I wrote
and if you don't know the basics of Unity why are you doing multi player?
i know unity basics
then you should know how to set a refererence in an inspector
irrelevant. The error message is perfectly clear. firePoint has not been set in the inspector
i have changed the error code to Runner.Spawn(bulletPreFab, new Vector3(0, 0, 0), Quaternion.identity);
it still give that error
its because bullet
if it was bulletPrefab the previous line would throw an error
bulletrb = bulletPreFab.GetComponent<Rigidbody2D>();
Runner.Spawn(bulletPreFab, firePoint.position, firePoint.rotation); //In here unity says 'Object referance not set to an instance of an object'
first line throws error if bulletPrefab is null
but bulletrb is bulletPreFab's Rigidbody2D and bulletprefab has rigidbody2d
but if bulletPrefab is null then there is no component to get. Nor an object to get one on
Ok, so possible multiple Player Controllers. Debug your code to see exactly what is happening and where
i will try
Why is this happening , when i drag into the ground the animation get stuck in the takeof is there a way to fix ?
this is what happens
{
anim.SetTrigger("takeOf");
isDragging = false;
line.enabled = false;
Vector3 startPos = line.GetPosition(0);
Vector3 currentPos = line.GetPosition(1);
Vector3 distance = currentPos - startPos;
Vector3 finalForce = distance * forceToAdd;
rb.AddForce(-finalForce, ForceMode2D.Impulse);
cameraShake.StartShake();
}````
I call the trigger in the drag end
{
if(Input.GetMouseButtonDown(0) && !isDragging && isGrounded())
{
DragStart();
}
if(isDragging)
{
Drag();
}
if(Input.GetMouseButtonUp(0) && isDragging)
{
DragEnd();
}
if(isGrounded())
{
anim.SetBool("isJumping", false);
}
else
{
anim.SetBool("isJumping", true);
}
}```
and then i set is jumping false if is grounded
why isnt it working?
well that looks like your if isGrounded code will override the DragEnd code
uhhh I dont get it, well if you need the whole script I'll share
so i have this script which has movement and jump but when the ground check is changed from 0 to say 1 the gravity becomes so slow why is nthat
you set the anim trigger in DragEnd and immediately after set the anim bool
steve may u help me also?
I'm good, but not that good
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
dw then thx
Does anyone know how to run code as soon as the object that the script is on spawns?
Put the code in void Awake() on a script attached to the object.
i f-ed up i excedently changed the name of a kinda importend script and now nothing works and changed it back but it still doesnt work... HELLP
normally unity transport doesnt allow variable string arrays to the network
it uses fixed strings
i bypassed that using this code here
public class NetLoader : NetMessage
{
public int length;
public NativeArray<int> LogLengthArray;
public NativeArray<NativeArray<byte>> ByteArrayArray;
public string[] RecievedPaths;
public NetLoader()
{
Code = OpCode.LOAD_FILE;
}
public NetLoader(DataStreamReader stream)
{
Code = OpCode.LOAD_FILE;
DeSerialize(stream);
}
public NetLoader(string[] log)
{
Code = OpCode.LOAD_FILE;
length = log.Length;
LogLengthArray = new NativeArray<int>(log.Length, Allocator.Persistent);
ByteArrayArray = new NativeArray<NativeArray<byte>>(log.Length, Allocator.Persistent);
for (int i = 0; i < log.Length; i++)
{
byte[] dat = Encoding.ASCII.GetBytes(log[i]);
ByteArrayArray[i] = new NativeArray<byte>(dat.Length, Allocator.Persistent);
ByteArrayArray[i].CopyFrom(dat);
LogLengthArray[i] = dat.Length;
}
}
public override void Serialize(ref DataStreamWriter streamWriter)
{
streamWriter.WriteUInt((uint)Code);
streamWriter.WriteInt(length);
for(int i = 0; i < length; i++)
{
streamWriter.WriteInt(LogLengthArray[i]);
streamWriter.WriteBytes(ByteArrayArray[i]);
}
}
public override void DeSerialize(DataStreamReader streamReader)
{
length = streamReader.ReadInt();
LogLengthArray = new NativeArray<int>(length, Allocator.Persistent);
ByteArrayArray = new NativeArray<NativeArray<byte>>(length, Allocator.Persistent);
RecievedPaths = new string[length];
for (int i = 0; i < length; i++)
{
LogLengthArray[i] = streamReader.ReadInt();
ByteArrayArray[i] = new NativeArray<byte>(LogLengthArray[i],Allocator.Persistent);
streamReader.ReadBytes(ByteArrayArray[i]);
byte[] dat = new byte[LogLengthArray[i]];
ByteArrayArray[i].CopyTo(dat);
string RecievedLog = Encoding.ASCII.GetString(dat);
RecievedPaths[i] = RecievedLog;
}
}
}```
If you're getting errors in the console, you should post them here
it allows me send string[] of any length and size to the client
but whenever i try to send more than 14 strings in the array
the data is not received
im getting 23 errors ):
any idea why?
Looks like you have a duplicate class!
There are two class CharacterController2D in your project
Deleting one will fix all the errors instantly
im also getting 132 errors in vsc
anyone?
Please have some patience
sorry
It doesn't seem like a beginner code issue, networking stuff should go in the #archived-networking channel as well
ok
literally what i only did is change this: (line 22-23)
playerSpawn = spawnHandler.spawnTransform;```
to this: (line 22) on the start()
``` transform.position = spawnHandler.spawnTransform.position;
and every time i made that change, it just made that one line error. anyone knows why???
spawnHandler is null
What's at line 35?
rb.velocity = movementInput * moveSpeed; //overall movement
The exception indeed occurs on line 35:
(at Assets/Scripts/PlayerMovement.cs:35)
What's rb?
rb did not have a value (it was null). You cannot access .velocity on null, so this error is thrown
this happens other time as well, where i change something at the script, that one line gets problem as well
rb = GetComponent<Rigidbody2D>();
private Rigidbody2D rb;
The object this script is attached to does not have a Rigidbody2D on it.
but it does, n thats what im confused at
Then you have another copy of this script on another object
And that's the one throwing
Make sure you didn't add it by accident
hmm lemme check\
nope, all clear
if it were happen, something else wouldve been moving other than my player tho
You need to place a breakpoint and load the rb variable
This could be fixed with basic debugging
It's null, there's nothing to load. Either there is another script and you missed it, or you put null yourself in rb at some point
GetComponent finds the component on this object. Not the parent, not the children
since theres an error, if there is another copy of the script elsewhere, only the player would move (as intended)
If you drag-dropped the Rigidbody from the Inspector, you do not need to use GetComponent in the code.
loading a variable is when a debugger captures information about any variable, whether it has an actual reference to memory, or not
Well we know it's null because they're getting the NRE, not sure of why the debugger would be useful here especially if there's only one place where they assign to rb
One place in the code, the field might be serialized and it's the code overwriting it with null
Idk wat i did but this is frozen een if i click play
what is that
Whole Unity Editor window is frozen?
no thr scene is fine
but the game is frozen
i can see my camera moving in the scene window
What should be happening?
i should be seeing my chraracter
Maybe you have an extra camera?
i checked i still only have 1
Type t:camera in the hierarchy search
using System.Collections.Generic; // //
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
private Rigidbody2D rb;
public float moveSpeed;
private Vector2 movementInput;
private SpawnHandler spawnHandler;
void Start()
{
//Spawn location handler when entering room
spawnHandler = FindObjectOfType<SpawnHandler>();
if (spawnHandler == null)
{
Debug.LogWarning("SpawnHandler isn't referenced in " + this.name + ".");
}
Transform playerSpawn = transform;
playerSpawn = spawnHandler.spawnTransform;
//Rb reference
rb = GetComponent<Rigidbody2D>();
if (rb == null)
{
Debug.LogError("Rigidbody2D component missing from this game object.");
}
}
void FixedUpdate()
{
rb.velocity = movementInput * moveSpeed; //overall movement
}
private void OnMove(InputValue inputValue) //triggers when an input happens
{
movementInput = inputValue.Get<Vector2>(); //gets the vector2 value of the inputValue
}
}
Could be part of a 3D asset you dragged in
o0o0o0o yea i did
It might import lights too
bet i found it thanks
oh sorry
this is what i meant
Make sure all scripts are saved, clear the Console and play the game again until you get the error. Look at the new line number in the stack trace of the error
and now,
it ... works???
i just redo all of the things i did multiple times
programming in a nutshell
ty btw, i added the if rb null cuz of u <3
How do I check static variables in the editor?
You can't, they're not tied to an instance of the script (which gets created when you attach it to an object)
So there is no way to debug them?
sure, in your IDE
They're available from the code, you can Debug.Log() them or inspect their values with the debugger
i want to execute a function every time any scene is loaded. how can i achieve that?
subscribe to onSceneLoaded
i was wondeing how does that work
{
SceneManager.sceneLoaded += OnSceneLoaded;
Debug.Log("SceneLoad subscribed.");
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneLoaded;
Debug.Log("SceneLoad unsubscribed.");
}
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
spawnTransform = FindSpawnLocation(spawnID); //look for the correct spawnLocation with the corresponding spawnID
Debug.Log("Current Spawn Location: " + spawnTransform.position);
}
}
did i do anything wrong?
As long as that code is DDOL it's fine
when i run the game, it only debug log the first 2 ones, so i think it didnt execute the OnSceneLoaded();
do i need to execute it on OnEnable() ?
It wont execute OnSceneLoaded for the current scene, only when you load new scenes
when i load new scenes, only these happens
it didnt debug the last debug log
so im assuming my function isnt executed
then your setup is wrong
you need a 'loading scene' with this code and it needs to be ddol, then you can load your game scenes
Yeah currently it does:
- Scene is requested to load
- Objects in the old scene are destroyed,
OnDisableruns and unsubscribes your method from the event - New scene is loaded and the event is raised, without any subscribers to handle it
It looks like it's unsubscribing immediately, so obviously it wouldn't react to any scene loaded after that.
which means he completely ignored the DDOL bit
so its my ddol setup for the game manager thats wrong
{
private void Awake()
{
if (FindObjectOfType(typeof(GameManager)) != null)
{
Destroy(gameObject);
}
DontDestroyOnLoad(gameObject);
}
}```
currently is this
that is insane
It works
it works?
what? find yourself and then destroy yourself
i setup GameManager in all the scenes
find the ones that isnt this one,
(in which i think thats the problem)
and deletes it
that is not what that code does
"that isn't this one" is missing in your code
ah yes
okk lemme try smthing
You'd usually pair that with the singleton pattern, to have a static reference available
I fixed it , I made a animation transition and set the trigger
but thanks for the help :)
I'm confused, why would you have had a trigger if you did not have a transition for it to use?
I added one
I make a transition from the takeOf to the Idle
and then I called it when the player is grounded
Is there a solution to do an action one time if the condition is true and after still the condition is true, do something else
For example ```c#
if(value1 == value2)
-> value1 += 1; (do this one time)
-> value2 += 2; (do this still the condition is true)
Sure, keep track of the number of times the condition was satisfied with another variable, and use that in an if statement
if (v1 == v2)
{
count++;
if (count == 1)
// do stuff 1
else if (count == 2)
// do stuff 2
}
And reset the variable back to 0 when needed
I do it with a boolean but it's okay.
I just wanted to know if it was something integrate in the C# or Unity to do something like this
Nothing that I know of, it's too specific to have it implemented in the base libraries
there are many ways to do this, for example
Action doAction = OnValue1;
---
doAction();
...
void OnValue1() {
value1 += 1;
doAction = OnValue2;
}
void OnValue2() {
value2 += 2;
}
Hello, i want to ask something about Unity and Visual Studio (Not code).
When i open file the Intellisense work fine (Just like the first picture).
But when i create new file and open the file those file intellisense not working for Unity Class or Namespace Like (Monobehaviour etc).
Example: in second picture
Anybody know how to fix this?
how do you create the new file?
note this is a part of the project
and this is not
I create it from the Visual Studio inside the script folder.
void Update()
{
if(Input.GetKey(KeyCode.Space)){
rb.velocity = new Vector2(rb.velocity.x, +10);
Debug.Log("Space Is Pressed");
}else{
rb.velocity = new Vector2(rb.velocity.x, 0);
}if(Input.GetKey(KeyCode.LeftControl)){
rb.velocity = new Vector2(rb.velocity.x, -10);
}else{
rb.velocity = new Vector2(rb.velocity.x, 0);
}
}
}
why does this not work?
dont do that, create new script files in Unity
File created using Unity Editor and Visual Studio also have this problem.
then you need to use the Regenerate Project option in External Tools
I forgot to add:
On my old laptop when i create file immediately from Visual Studio its always immediately connect and has Intellisense for Unity
I already do that too, but it didn't do anythinig. The only work around i found is close and open Visual Studio everytime i create new file
But it wasn't a solution :<
That should not be necessary, which Unity Version and VS version?
Visual Studio version: 2022
Unity Version i use is 2021.3.27f1 and 2022.3.43f1 Both have this issue
more to the point, why have you not yet learned to
A) Ask questions properly
B) Post code correctly
Odd, tbf, I dont use VS 2022
I have a turned-based combat system and that is how I load in an enemy, as of right now I can only load one enemy, what is the best way to control which enemy I load into the scene each time?
I would suggest you divide your work into separate managers that manage what happens
One spawns enemies, another one shows it on the hud
so like create an enemy manager?
Yes, pretty much
Hmm... yeah my friend pc that has Visual Studio 2022 installed for Unity didn't have the same problem as mine. And we too didn't know how to fix this.
But this is not as relevant. If you want multiple enemies, make more prefabs that represent these enemies. Then you could, for example, set up a dictionary and set them under a key. Then your manager takes this key and it will get the corresponding prefab
This is just one way, obviously.
But I'd recommend you don't couple your code like you do now, because now it's hard to fix your issue.
Or you pass all your data into SetupBattle, but that method should not worry about this
and like how do I actualy load the enemies cuz the only way I thought about is to build a method that gets a name and then a very long if list that checks if the enemy need to be loaded by name
Well I don't know what your game is like. But if you want a quick and easy way to get enemies, use a dictionary and store them under their name
tbh, everytime you add a new script in Unity it should update the .csproj file in your project.
One thing I can suggest is close Unity and VS and delete the .sln and .csproj files in your project and then open Unity and then VS from Unity
Using a list gives the issue of filtering, or knowing their index. A dictionary allows for a known key to be set.
now not complex at all but idk if it will stay like that
If they just differ in sprite then you could just keep it simple and specify the sprite name to render in a script
But if it has varying behaviour or even more than a single sprite I would probably make separate prefabs and store behaviour in its own script for each enemy
I think I will do that then
You can just store the prefabs in a dictionary. If your manager's Awake method is called you could fill it in, for example
but shoud I load them in using instantiate?
Feel free to ping me. Just make sure to not overcomplicate it
Only when you need the enemy, probably
Well, remember there are multiple ways of tackling this. Right now I gave a solution that's quite big but scales well, so you can also start simpler if you want
1 more question
every time the enemy is loaded its loaded by its name, and cuz of that I cant use GameObject.find is there a solution to that?
Hmm... i have try deleting both all the .csproj and .sln in my project and regenerate it, but the issue still persist
You should not use Find methods first of all. They are slow, and if you require this method often it will slow down your application
Instead the manager helps here quite a bit actually
You can make your manager a singleton: https://unity.huh.how/references/singletons
What happens is that your manager can now be accessed from anywhere. This works well because you only have one manager to manage your enemies.
Anyway, this manager spawns your enemies. What you can do then is when you spawn your enemy, you store the instantiated gameobject in a list in your manager.
The only thing I can think of is for some reason updating your .csproj file is being blocked
So now, if you want to find your enemy again, check this list. If you want more control you can once again use a dictionary with custom keys. Alternatively, store them under their "type" in a dictionary, and then it could return all enemies of a given type.
You can also try using your Find method, but remember that calling it is slow. Prefer caching its result if possible.
Hmmm.. anyway to check this?
yes, create a new script in unity, then check in the csproj file if that script is referenced in it
ok
I create new file name "Testr.cs" and when i check the .csproj
It was referenced, seems like the csproj not blocked.
Edit: Add more detail
bro pls help
I told you what you needed to do
i cant find a dupe of anything
You have two classes with the same name, remove one
pls help the i would like reset my paswort but its dosentworking
Perhaps check through file explorer. Unity might not show the file.
This is a coding channel. #💻┃unity-talk
Ok so what happens when you open that script. Screenshot the full VS window
i dont think its just 1 dupelicate
Actually the Testr.cs file Intellisense not working too...
since it cant get unityengine namespace
The errors are caused by the duplicates. It sees that the class is there twice, and it thinks all its members (fields, methods) already exist, so it throws errors everywhere. Removing the duplicate file will fix all the errors.
Currently all scripts cant get UnityEngine namespace
Check my message. If you can't find the file it might help checking through file explorer. Unity might not show it.
ok, try this
In the Solution Explorer on the Assembly-CSharp project, Right click and select Reload with dependencies
i checked it over and over again, even asked chatgpt and it still doesnt work
Did you check through file explorer if the file exists?
Sadly its still didn't work
Open your project in file explorer, navigate to the folder and look for the file.
My man, it's not a code problem. You literally need to use your eyes to spot the duplicate file
So what's the problem? Why don't you check?
Surely you could spot a file that doesn't belong if you check in it.
i mean the file exists
I'm talking about a file, possibly with - Copy suffixed, sitting in the folder
How about you check and then come back
Sorry, I'm out of ideas except to say, install VS 2019 instead of 2022 because I've never had problems with that
I scrolled back up to your original screenshot and it's literally here. You have a PlayerController2D (2).cs aside the "correct" one
Just get rid of it!
Yeah I don't understand what's so hard about checking the folder because this would be very obvious
i have fixed something apperently cuz i ony have 3 errors left
"apparently"
lmao
Yes, you removed the file
Yeah those are legitimate errors not linked to the duplicate class
Ok, thanks for the help @languid spire. For now i will try installing VS2019 first.
Well done, now all that's left is an actual coding issue
broo im new to this alright? sorry i took me so long
yeah, this is the 'lets just do shit until it works' school of gamedev
Just have to follow instructions, it's not hard
You'll run into issues very quick if you don't apply them, unlike human beings, computers will do exactly what you tell it to do
Is there a way to change what is connected to a game object trough code?
like this for exapmle ^^
enemyprefab = differentobject;
Are you trying to load that gameobject from your assets
yes
i have a turn based combat game and im trying to figure out a way to load a diffrent enemy each time
Well you could make a list and have EnemyPrefab1, EnemyPrefab2, EnemyPrefab3 and so on
Then load different EnemyPrefabs
yeah i would do this and assign it in the inspector, the alternative would be Resources.Load which is bad because the entire resources folder is in memory all the time
Get a reference to the script and then change the variable that is displayed in the inspector.
If the variable is private or inaccessible, then you can't change it from code without reflection.
lol, where to you think the contents of the List are?
I created an enemy manager and created a script for it, should I also add the battleSystem script as a component?
Also, you don't need Resources.Load. If you know the enemies beforehand you can set up a list or dictionary and assign enemy prefabs there that must spawn.
not in the memory if you're in a different scene that doesnt need these enemies 😄
is this what I should do though? @burnt vapor
Where do you guys suggesting going if I want to pay someone to code part of my game?
dont crosspost
and this channel is only for code questions
For example. Try making a singleton with the link I send. Then make it an enemy manager
Lastly try to store spawned enemies in a list and then see if you can set it up in that loader code you showed
ok i will try
!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.
UGH
Lerp is STILL having the Max be 1
or Really?
LerpUnclamped?
Ill show code
private void motionPhysics()
{
body.AddForce(Vector2.right * CharacterSpeed);
if (movement)
{
CharacterSpeed = Mathf.Lerp(CharacterSpeed, top_Speed, velPower * Time.fixedDeltaTime);
}
testingUI.text = CharacterSpeed.ToString() + " " + body.velocity.ToString();
}```
I want the Variable shown to be what Top_Speed is which is 11.0f
Ah, it's a case of "wrong lerp"
https://unity.huh.how/lerp/wrong-lerp
Perhaps you want to use lerp correctly, or use Mathf.MoveTowards for constant change
Hi I have a question
So I get the transform component reference of a child object then I tried to change its x and y position by inputs but whenever I change any position by pressing key it also changes z axis position while I put it as objectTransform.position.z
Please🥺 help me
!code show code and ur hiearchy / set up of these objects
📃 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.
I want to make it so, when (Private bool ColliderUse) is TRUE then object(s) are enabled
is there a issue? not sure what you are asking
I dont know how to do that
well !learn how to use unity
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
just send your code
Dude... I want to make GameObject WaterCollider turn off when ColliderUse is true
you need to learn how to use unity, not only that we have no context to your issue and no code.
we will not just make code for you
I am adding a Swimming feature and I don't remember how to use SetActive on a GameObject
do you want it destroyed or do you want it to be disabled
gameObject.SetActive(false) or true
Disabled, and it re-enables when you leave the watet
use docs for something you dont know
You don't even need to ask this here, you could type it in the internet
best use docs next time for something you dont know
Hello , can i use the start method in a scriptableobject ?
I don't think so, but you can try it. Place a log in it, and see if it gets called at the right times
If it gets called at all
nope
Awake does though
this is a code channel
oh my bad
I am completely new to unity and i was trying to add a physics material to my rigidbody2d but it doesn't work
what "doesn't work" mean
meaning i tried draggig it into the slot and it showed a blocked sign i think
and it wasn't in the menu
probably because you made a 3d physics material and not 2D
i could only see one option
is it in legacy or something
its under the 2d menu
How do I access a prefab in a folder in my project trough code?
does that work with 2d?
so should I use Resources.Load?
hello
I have an empty object for ground checking but how do I make it that the empty goes with the player and not anchoring in some place
it dont move with the player
what are you trying to do and why can't you just link it via inspector
parent it to the player
it is a child of the player
you have it parented to the mesh not the bones that actually move
doesnt the mesh move too
not really the mesh is just a "skin" placed above the bones just visuals
thank you
😂
jembey!?
How can i access the Application.version outside of main thread?
It says call it from Awake or Start
Yep exactly
So there is no way to get the version of the game outside of main thread?
then in the start/awake, appVersion = Application.Version;
are you doing string appVersion = Application.version in initializer?
you can access appVersion later on
Yes
That gave me a simple idea! I believe i should use direct string and keep it updated 🧐
oh yeah cause its a static method
Not sure what exactly you mean but if it works great
Bet it is because their backend takes that information from their "unity instance"... this is bullshit
you can make it a property tho
public string AppVersion => Application.version
I'm trying to create a method that load an enemy prefab into the turn-based combat scene based on his name
if thats even possible
okay but I still don't see why you can't just make fields in the inspector and drag the prefabs in there directly
GameObject enemyObject = Resources.Load<GameObject>(path);
Create a folder called resources and place that prefab in the folder
Good point
you mean like drag all the diffrent enemies into the inspector then load the one I need?
yes
isn't it a bit impractical when i will have dozens of enemies?
how is what you're doing more practical ?
umm idk I guess if i will have them stored in an enemies folder then I can load them from that folder will be easier?
yea but if you change name or move it as some point it breaks
It also depends how you distinguish what you're trying to spawn
that doesnt work for me though
I did but I didn't understand much
it literally shows example how to grab it
Read this again please
also if its a UNIT not point of grabbing it as GameObject you can just grab it as Unit
That was the first thing that came to my mind
timescale otherwise not unless you make your own ticks
Damn okay I might just purposefully lower fps then
that sounds awful game experience
Why don't u type this in google
tbh at this point I think coding is my kryptonite
Google didn't really give any results besides time.timescale
ask chatgpt?
Nor did chatgpt, actually it suggested me to manually lag.. XD
It didn't work?
you mind as well get your advice from a dog
I mean I put it in Recources folder then assinged it to the enmy unit
I guess so
and its still gives the same error
show the code you wrote
no one can do anything without seeing what you did
why did you asign it
The point of Resources.Load is to load it from the Resources folder
its the same as here I just moved the enemy prefab into the Recources folder
so you didnt read again the docs on how to correctly write it ?
The path is wrong
but I cant change it if I dont assign it into the enemy unit
even though the page tells you exactly how to write it
thats right
if Dwayne.prefab is in the Resources folder
then Resources.Load<GameObject>("Dwayne")
You don't need the ".prefab"
just the "Dwayne"?
maybe they would've read it but they like spoon feeding
without the Assets/Resources?
if you want to get anywhere in code/development you have to make it a habit to read, especially the documentation/manual
I get that but tbh when I read code examples I feel like my english level is degrading
and tbh every time I look for an example it uses another method that I dont know in the example
how so? I sent you the exact method that you would've used and you still wrote it wrong , even copying example code would've been more correct than what you wrote
🤷♂️
I guess you are right
Hey Guys! Im struggling with List.Add..
I know how to do it with gameobjects/ strings etc but my list is based of a custom function " dont know if that is the correct term, sorry"
and I dont know how to add it correctly
The setup:
public List<Digit> digitData = new();
[System.Serializable]
public class Digit
{
public int representingNumber;
public float rotationAngle;
}
Where I want to add and set the parameters
private void AssignDigits()
{
for(int i = 0; i < NumberAmount; i ++)
{
digitData[i].representingNumber = i+1;
digitData[i].rotationAngle = i * rotationAmount;
}
}
Right now I set the list size manually in the inspector but that isnt ideal
I mean, I'm just telling you because I've been there before, not trying to come at you
unity docs tbh is one of the actual ones that are pretty clear in comparison
ye I get that You helped to much to come at me
dont send screenshots of code please and use ⏬
📃 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.
your list is based on a custom Class not a function
aka a type
.add should work just fine, make sure you are actually creating an instance new() of the item you want to add to list
I would recommend the foreach loop
Also, you are changing the variables of null elements
digitalData[i] does not exist yet because you didn't .add one yet
they have elements
Or you added it somewhere else in your code and I can't see it
they said it was added in the inspector
they are probably struggling creating a new instance of Digit to pass to Add
They said they set the size
@still wren u managed to solve the out of bounds issue?
without knowing what OP true issue was with Add without detail, pretty sure the issue is they probably did not know how to do a new instance and add it to the list via code
I would create a constructor new Digit(int repNumber, float rotAngle) then digitData.Add(new Digit(i + 1, i * rotationAmount))
idk I thought the elements were null
in the code snippet you sent, you used ++i which, first increments the value of i, and then processes the info
I think
someone correct me if im wrong
correct but you can iterate over the items and assign them since the list elements ae there, is just null
Thanks for correcting me about the code snippet, and teaching me about the correct term 🙂
and yes that is correct Im struggling to create a new element in the code, I thought that it would have looked something like this but I was wrong
private void AssignDigits()
{
for(int i = 0; i < NumberAmount; i ++)
{
Digit temp;
temp.representingNumber = i + 1;
temp.rotationAngle = i * rotationAmount;
digitData.Add(temp);
}
}
almost correct, you just need Digit temp = new(); //creates new instance of Digit
that creates a new Instance of that class
you can also assign a constructor to it that can take in the data you want as parameters as shown in example above
I phrased my sentence in a wrong way nvm
YES! thanks I can now stop pulling my hair
works like a charm
might want to do a quick crashcourse on c# 😛 check pins in this channel as well
heh yeah I really should, I know quite a lot but then at the same time I know very little about some of the most basics things xD.
self taught 😬
haha yea I feel that as self taught its harder to know which topic to go for, doesn't hurt to refresh on a few things in the beginning just have to engrain them in the mind by repetition
is there a way to access a variable via a string of the name or id?
so for instance:
public class TestClass
{
public int variable1;
public float variable2;
}
public class OtherClass
{
var variable;
void GetVar(string id)
{
variable = // get variable based on ID
}
}
the best I can think of is to make a function that returns T with a switch case in it but that's not very dynamic
you could store them all in a list i guess or something
Use a dictionary. The key can be a string or an ID. Take note: if it's a value type, the returned value is a copy . . .
so I wouldn't be able to set it?
ofc you can set/read it, the Id is the same would it not

I can see how u can make a dict for reference types cuz u can pass through the reference, but u can't do that with data types right?
wdym "data types" there are only two, value types and reference types
value type* mb
also u'd have to make a dict for each type, unless u can make a <string,T> dict? that sounds silly
It would be very limiting if you couldn't store value types in a dict. So of course you can do it.
Dictionary<string, object>
ooh object
that or , just make a containing class or struct
public Dictionary<string, float> valueTypes = new();
public Dictionary<string, Transform> referenceTypes = new();
private void Awake()
{
Vector3 position = referenceTypes["someId"].position; //gets copy of pos (v3 is a value type)
referenceTypes["someId"].name = "Something";//changing the original
position = new Vector3 (32f,32f,3f); // does not change original pos
float value = valueTypes["someId"];
value = 23; //does not change the original, its only a copy
}```
the idea is that I made a chat system so I can create commands like in minecraft so I was wondering how I could set up a dynamic way to set variables from the game itself.
so like /SetVar [script reference] [variableID] [value] which would be nice for debugging in a build
is a delegate an object? 
you're using OOP everything is an object 😛
fair xD. so I'd have a <string,object> dict, could I put it in an interface ICommandable so I can gather any ICommandable script in scene?
I remember being able to make value types in interfaces as long as they do the {get;set;} thing
interfaces have nothing to do with having value type or reference types inside
as long its a property or method it can be there
so a dict property?
the difference between a variable and a property kinda go over my head, they seem like the same thing most of the time to me
fields are just variables that can be either read or assigned, properties can do the same but are like methods that run each time you do one of those.
field + onset/onget method = properites
so you can cram extra logic inside when you get or set a value
if that's the only difference, why can't an interface have fields but it can have properties?
An interface can't contain constants, fields, operators, instance constructors, finalizers, or types. Interface members are automatically public, and they can't include any access modifiers. Members also can't be static.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/types/interfaces
properties can be thought of as wrappers for methods
and interfaces can have methods
that's my understanding, at least
using TMPro;
public class green : MonoBehaviour
{
public TextMeshPro tmp;
public int amountToAdd = 1;
private int moneyAmount = 0;
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name.Contains("Circle"))
{
if (gameObject.name.Contains("green"))
{
Destroy(collision.gameObject);
moneyAmount += amountToAdd;
tmp.text = "$: " + moneyAmount;
}
}
}
}
``` the code works but majority of the time when the circle collides with the green it can remove from the money amount ex: money at 3, circle colides with green, money goes down to 1. does any1 know why this happens?
Properties are basically methods. They don't store any data and don't provide any implementation on their own.
how many "green" do you have, also that if statement looks cursed. I don't see anything subtracting money here
six
why cant i type 6 lmao
so you still have them change the same text with their own new values?
then what happens when, for instance I have a property string name {get;set;} and I do name = "Steve". does it not store that string?
you can't assign any values (oh thought you were talking about interface initializer)
thx that fixed iot
Auto properties actually have a hidden backing field. When the compiler compiles the code, it adds that field to the code.
Thats an automatic property.
Properties are basically a syntactic sugar. In Java you have to use actual methods for that.
There's a lot of features like that in C# that the compiler does for you.
I was actually coding a web API for a database a while back in java and I was wondering why I had to make a get and set method for each variable
I guess C# is just very nice xD
microsoft java is much nicer 
Yeah, you can think of C# as java on steroids.
chadJava
We have 1 line encapsulation 😎
tried minecraft modding, java is not nice
still no clue what registries are but glad I don't have to deal with them in Unity
my only modding was some light C++ (source sdk) , after finding unity c# in comparison was so easy lol
henlo, a quick confirmation question
transform.position = spawnHandler.spawnTransform.position;
this will change the current object's position to SpawnHandler's (script) spawnTransform (a Transform) position, correct?
GameObject gameManager = GameObject.Find("GameManager");
spawnHandler = gameManager.GetComponent<SpawnHandler>();```
Yes, whenever this line runs, it will set the position of this object to the position of the other
hmm, ok sec
as long as spawnHandler is not null by the time you do it 😉
to be clear it sets it to spawnHandler's position not spawnTransform
I just started learning C++ because I feel it's good knowledge to have (about resource management). It's different. There are so many keywords, and writing a method with parameters looks like magic: cpp shared_ptr<Room> ChangeRoom(player&, const dungeon&) const;
I should give it another go, the source engine made it easier to just use certain premade functions that existed, but had no idea how to even create new data etc.. need to start from the basics again but idk I'm already in the middle of dealing with C (maybe C++ soon) for microcontrollers
I'm working with C++ every day and this function signature looks weird to me.🤔
Where's the function identifier/name?
It's not that different than C# until you get into templates. I hate templates.
And macros
Just need to know what the const keyword does in each situation and references/pointers obviously.
Oh, I just forgot that part. I was just coming up with smth ridiculous. Like const means three different things depending on where it's placed . . .
Yeah, const is annoying. In general, C++ compiler expects you to be very punctual.
It's like, "I'm sorry, but you have to make a vow that you're not gonna modify anything in this function".
My biggest thing is learning when to use a reference or a pointer since a pointer is a reference but with more power, haha . . .
I'd say the same as public fields in C#. Avoid at all costs, unless absolutely necessary.
Though, maybe that's an exaggeration.
Since nullptr can be useful.
I guess passing a value type by ref vs using a reference type instead, is a better analogy.
They say that then throw a curve ball with mutable . . .
Yeah, though to be fair I barely seen mutable being used anywhere.
I couldn't see using it at all either . . .
Once I get the control flow down, it'll be more manageable. I will say, refactoring is more complicated. I get lost going from file to file and trying to avoid classes included multiple times from other header files. I have a StateMachine that needs the header from State and vice-versa, so I have to figure that one out . . .
reading json is much less enjoyable than writing it half of functions not work
how do i make my jumps jump more like how it jumps in this video?
this is my jumping part of the code
if ((Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown(KeyCode.W)) && is_grounded == true)
{
rb1.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
is_grounded = false;
}
my jumps right now feel very weird and smooth, which is not what i want
honestly, i just want to make a text-based dungeon crawler. move to a room, choose from a list of actions, do those actions, and continue until you make it out of the dungeon. the goal is to have a set number of floors to climb up until you reach the top with rest areas further apart
you're messing with C? that's even lower than C++ . . .
what does it mean exactly, like the height? or like what
or do you mean the hold button to go higher
it's hard to explain, but the gravity ig
you need to change the mass and stuff on your rigidbody
you can probably find the exact numbers online
if they use a rigidbody also
yeah they do
when i add more mass, i don't jump as high, i want to jump the same height, but i want a higher gravity
then change your jump height also?
also change gravity and stuff
how
you can do it in project settings i think, not sure if thats the ONLY place or not
is it in the rigidbody section?
i think its just under physics in project settings, not exactly sure
probably in the docs
2d rigidbody has a gravity scale property you can assign to
it's lowers my height by a bit, but i will try to fix that
thanks
what i personally like to do is keep gravity scale around 1 when grounded or performing a jump, then at the apex of the jump (or when pressing down) increase gravity scale so the object falls quicker. you can also compensate for your reduced jump height by simply increasing the amount of force applied
thanks
but, how do i access the gravity scale from a script?
theres videos for that on youtube you can find if you want, ive seen it before.
its a pretty common technique
same way you add force?
didn't know you can do that, thanks
Via code you can access everything you see in the inspector + a lot of stuff that you don't see.
Check the documentation for the available API.
a good idea for learning project to do for sure, I did a much simpler text based rpg with one of my first projects in C# console, taught me a lot, esp working with loops something I wasn't comfortable with in the beginning.
And yeah for current project I'm working dealing with hardware and microcontrollers, is to be used in Unity. For this I need such low language, it really makes you appreciate such high level languages like C# at least lol Its good feel though to have such little programs be so efficient and fast.
Eventually the plan is to move onto playing around with more bare metal controllers and C++ seems the next step
guys how to check for fps in a build
which platform?
Attach the profiler. Or implement a custom fps indicator.
URP
Windows, Mac, IOS, Android, WebGL?
I have a problem; I tried using Firebase's real-time database, but it's not supported on Android. Do you have any alternatives you can suggest, or how do you handle databases in your games to ensure it's convenient?
would anyone happen to know what the hell is going on here? anything labelled "Input" is a textmeshpro text input. theyre all strings, shouldnt they all work?
This happens for both RefreshContainer() and RefreshValues()
RefreshContainer() is called whenever a text input is changed
Do you need to use the database in the first place? What is the use case?
auth2 + save load system
when doing this, the error disappears, but im pretty sure the commented stuff should be correct right?
TMP_InputField.text actually has a null character in the string, you need to Trim('\u200b') and it should work
...interesting.
Not sure what auth2 is exactly(some kind of authentication system?) and why you need a database for it, but database for saving and loading is probably not a great idea. Are you developing an MMO with thousands of players?
Is the save data supposed to be saved on the cloud or locally is fine?
like this?
yeah...that didn't work.
have you considered using the debugger to inspect what the string actually is? or even printing it?
i didn't think I'd need to, but here it is anyways
also id like to note that the lines for the .name work perfectly fine, but only when the other lines are commented
the name property can have whitespace in it. whitespace is, notably, not an integer though
it does not have whitespace
how have you confirmed that
well then i guess your string is in the correct format for int.Parse! congrats on not having an issue, i guess
uh, thanks? my issue isn't fixed though-
so then what do you think that indicates?
because you've printed the strings and see that the only visible characters are integers, and yet it's still not in the correct format for int.Parse
i'm not sure we're on the same page, the issue isnt just for int.Parse
are you still going to try insisting that there is no whitespace in your string?
also, yes the issue is just for int.Parse. it's literally what is throwing the exception
the code after the int.Parse line cannot run because an exception was encountered
i'm trying to be polite here. there are two fuctions, both of which fail. One of them does not use int.Parse
you have not shown any stack trace that has anything to do with any other method
holy shit dude, did you even look at the most recent part of the stack trace?
your issue is literally still int.Parse because you are modifying the text object which invokes the event which invokes the method that invokes int.Parse
also note that when this screenshot was taken, RefreshContainer() was NOT being called and the Parse lines were commented out anyways.
can you read?
ah, then that's my mistake; i didn't realise that modifying the text directly would trigger the callback. thats genuinely my bad
however it's still not explained, since again, the parse lines are commented out.
i will ask once more, can you read?
yeah so anyway, the issue is whitespace in the string
that Trim call you have only trims that one whitespace character (which is sadly not trimmed with the default Trim() call)
its my first time using raycast and I'm trying to use a layermask to trigger a function when im looking at a specific function, but it seems to trigger anyways no matter what object i'm looking at or what layer its on
show code
// Update is called once per frame
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
if(Physics.Raycast(ray, raycastLayer))
{
turnOnLights();
}
}```
specific object*
you've actually just provided a maxDistance because the first optional parameter for Physics.Raycast that accepts a Ray as the first parameter is the float distance. LayerMask has an implicit cast to int which also has an implicit cast to float
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html
You need to either provide a maxDistance before the raycastLayer parameter, or use Named Arguments
if(Physics.Raycast(ray, maxDistance: 100, raycastLayer)) like this?
well if you do that you don't need the named argument
but also if you do use the named argument there, you'll need to do so for the layerMask argument as well
it still wasnt working but it was actually an issue with the mesh collider
thanks for the help
does anyone know how to have a game object reference another object by name only under its group? So for example, it searches for attackpoint1 under player but not outside of it.
Ideally you would get a direct reference to the object instead of trying to find by name. but have you looked at the docs for GameObject.Find or even Transform.Find?
I was using gameObject.Find but when i use that, it also searches stuff outside of the group.
i'm guessing that's a "no" on the question about looking at the docs for that method then
Windows
ugh copying it added an extra slash at the end for some reason. it works now. use that page to learn how to get a reference to the object without using GameObject.Find
and if you insist on using GameObject.Find then look at the docs to learn how to do what you are asking
yeah i think i got it now ty
i got this problem, can anyone help me, havent destroyed anything so i donno what will help 😄
i havent made any code ye, just makin map
if possible, can someone give me a hand with this?
https://www.reddit.com/r/Unity3D/comments/1f6jnxq/rig_builder_rig_not_moving_with_mesh_yet_still/
pretty please ofc
with a cherry on top
That looks like a unity bug, restart Unity
aight ill try it
if i have a class with no constructor like
public class MyClass<T>
public List<T> MyStuff = new List<T>
and i have an instance of it in a class (in this case static but curious in general) like
public static class MyStaticClass
public MyClass<T> MyClassInstance
do I need to initialize it w/ a constructor like public MyClass<T> MyClassInstance = new MyClassInstance<T>() for the class and list to initialize or can i skip that if it doesn't explicitly have a constructor
it worked for now 😄 thank you
Not initializing a class with the default constructor results in (MyClass<T>)default created, which, in case of classes is null, and throws an error when done within the local method
yes you do need to initialise it
guys how would the player detect a projectile when standing still when using a character controller for the player
am i just supposed to create a script that attaches the rig to the player every tick?
can you code that a componement gets added to a object?
for example that a script gets added to an object
gameObject.AddComponent<ComponentType>();
it returns all the tim e
which Unity version are you using?
2022.3.42f1
It is obviously a bug in the Terrain Tools package, you could look to see if there is a newer version otherwise you're stuck with it
yes
there isnt
tbh it's not a critical error. Looking at the stack trace it's just trying to save some settings so it should not affect your project at all
does setting position to an empty gameobject each frame is the same as set parent transform?
i want to pool the sprite object and make it follow the enemybase, which is in network pool, so when i create enemybase i want to set spriteobject to it and make it follow the enemy base without setting parent because i think it might affect performance
if i have
MyDerivedClass : base
string coolstringname
can i swap in a base and re-serialize the value like
MyBaseClass
[FormerlySerializedAs("coolstringname")]
string baseString;
MyDerivedClass : MyBaseClass
(yes)
It should. FormerlySerializedAs attribute keeps the old serialized value in the variable you put on. Useful when you update the variable names. At the first when i saw this attribute, i thought it was a name changer tho :d
not sure it will work though when you swap out the base class
Do you know how can I limit my linerenderers line and prevent it from going through walls and if I can add a gameobject to the end of the rope. I'm using it as a grappling hook
to limit the line renderer you would need to raycast each point in the points array as you are building it. To add a gameobject, simply position it at the last point in the points array
Hi. I have a problem. In Unity, any changes that i make don't apply to game and i couldn't find a solution. Could you help me please?
What exactly doesn't work?
That all seems to work from the limited info provided
Any codes that i write, for example in these pictures. I write a Debug.Log("Interval is working"); it works okay but then I removed from codes but it still works. Console show me this debug
So you removed debug.log and it still logs?
I don't understand what you're trying to say.
Yes, I wrote it to show here as an example.
no it doesn't
Then maybe you have turned off auto refresh/auto recompile, whatever it is called
Or there are compile errors that prevent the compilation.
Yeah cant see from the screenshot if you have errors
There is no any compile error
it is enabled
Well, then add some new log to the existing logs and show us that it is not being printed while the other 2 get printed.
What IDE? Is that Rider?
yes
Doesn't work :(((
But your other logs are gone..?
I disabled all other GameObjects
Double click here and take a screenshot of the inspector
unhiding the warning in your console might be useful as well
version 6.0 but i tried other version
yes it's working if I press ctrl+r
Okay so auto refresh isnt working
yes but why of :///
So Edit > Preferences > Asset Pipeline > Auto Refresh is enabled?
thank you bro, you saved my life
You said it was enabled earlier 😄 But yeah no problem
i looked here
😄 sorry it was my bad
why cant i just get json by providing exact path like i did when writing it
thing["a"]["b"]["c"] = stuff
instead i have to mess with selecttokens which is so unintuitive
Now you have a reason to write your own Json library
im already using this custom one because unity one is even worse
where i need to specifically write down classes for it
Nothing beats rolling your own if it's specific functionality you want
my own one looked pretty much string.split("key")
was nice to use but definelly not performant
actually Nettonsoft is open source so just grab a copy and mod it
