#💻┃code-beginner
1 messages · Page 94 of 1
yep i started putting the big stuff over there
the only game i got is genshin 🙂
Btw, I still recommend you going through C# basics/manual.
Ideally you want to understand 100% of the tutorial code by the time you finish it.
i think i have one of those kicking around. only reason i havn't dug it out is because i'm clumbsy and my last one took a small tumble... lesson learned the hard way. don't get one with a mechanical arm drive. it got bent
rip the stuff on it
my rig was and still is kinda ghetto, i use a fold out dinner table for my laptop, so theres not any practical solutions for storing and using external drives other than sitting it on my lap with a long wire
darn gifs aren't allowed here. was gonna insert a gif of muscle man
also removing older editor versions / unused projects and such since that can eat your space pretty quickly
possible to refer to a different light source instead of GetMainLight(); in unity 3d unlit shader graph?
for example a spot light
also im guessing that i wont be able to refer to MULTIPLE light sources would i
my bad guys :C
how could i check if any keyboard key is pressed? bc if(Input.anyKeyDown) returns true if mouse is pressed aswell
Hey guys, does anyone have a simple camera/wasd movement script with gravity that I could just copy into my game? Thanks, I haven't been able to find a good one after googling it for about an hour...
make one
I want to, but I don't have time rn
Hey guys. Quick question.
I have a prefab that spawns a "pet" when the player purchases that "pet". I can animate it to walk around and spawn at a certain place on the game view by using a spawn point.
But im trying to make it so it walk around in like a little "pen".
So i will be creating a enclosure for the pet.
So when the pet spawn i want it to freely walk around in that enclosure.
Is there a way to achieve this? I dont want it walking past the enclouse fence. So if it reaches the fence it will turn around and walk somewhere else. Like its trapped in a box and it cant go past a certain point of that box.
Or will i have to animate a path for each and every pet i make?
Or is there a way to make say a movement script for the pet to freely wanter around in that enclosure (box)
easiest way, give the enclosure a NavMeshSurface and the pet a NavMeshAgent. Then you can chose random points on the surface to use as the destination for the Agent to walk to
I'm trying to make my player script call a function from a script on another object. The player script doesn't know what the script is called, but it does know what it inherits from. I've been using SendMessage() to achieve this, but I'm not a fan of using strings to call functions. Is there a better way to accomplish what I'm trying to do?
SendMessage is usually for lazy debugging
you can use GetComponent with the base class and it will find any script which inherits from that class
I wouldn't mind it too much on smaller projects, but it's a linear search through all methods and components so it can get out of control
Oh god I tried this, but I just noticed that I forgot to include in the code that the script I was looking for was in the collided object's parent...
how could i check if any keyboard key is pressed? bc if(Input.anyKeyDown) returns true if mouse is pressed aswell
You could just additionally check if(!Input.GetMouseButtonDown(...))
tysm
Maybe theres a cleaner way, but that doesnt seem too bad.
could make your own input method with all the keycodes you want ;)
one more question
when i have a button and i click it i have it "selected", when i then click space it clicks it again, same with the slider, once i have selected it i can move it with "a" and "d", how can i disable that?
I was wondering how to get it to look at a TextMeshPro -Text UI file i tried to use just Text but it isnt working
using TMPro;
private TMP_Text cherriesText;
thanks
See "Navigation" in the inspector
Does anyone know why this material is returning null, despite the filepath being copied and pasted?:
Material textMaterial = new Material(Resources.Load<Material>("Assets/TextMesh Pro/Resources/Fonts & Materials/Futura Medium Test.mat"));
Where do you see it returning null?
Also, I don't think that's a valid path for loading via resources.
It's supposed to be relative to the resources folder.
why i cant add TMPro, i wanted to replace old text component in GameJolt API but i cant add TMP
Do you have TextMeshPro installed?
Is this script part of an assembly definition?
idk...
If so, add TMPro as a dependency
how?
How do you mean you don't know? This is your project
this is GameJolt API, i wanted to replace old text component in api with TMP, i already said that
It is part of an assembly definition, because it's part of GameJoltRuntime rather than Assembly-CSharp
Are you editing a library you installed? You should not do that
You should either request a change or find a proper implemented solution
this is plugin
That doesn't really tell me anything
Show me a picture of where this file is located in your editor
You need to find the Assembly Definition, it should be inside the folder of the plugin and add TMP like so:
Hi. Is there a way to know if an object is like to the right or to the left relative to another's object forward vector please?
like I could use some inverse transforms, but when I rotate the object it is taking the inverse from, the right and left are inverted. Like I would need it to be in world right and left, I don't know if I'm explaining myself😅
guys why I can't fully move my mouse up and down? maybe something with the script x y ?
@glossy eagle you could compare positions, if object position.x is less than this position.x it is to the left and so on
that wouldn't work because it is in 3D so position x being greater than the other one wouldn't always mean it is in its right relative to the forward vector, but that gave me an idea on how to do it I think, thank you so much 😄
i have a script that generates a Capsule by code, but i need to add rings to the "cylinder" part of the capsule, how do i do that? im very new to mesh generation
So probably a really scrub question:
I have an IEnumerator that doesn't seem to function correctly, I can call it properly but it doesn't go past the "WaitForSeconds" part in my character controler state machine.
I moved the IEnumerator to the root of my state machine to make sure it doesn't get deactivated and the time should work correctly so I'm not sure why it isn't going past it.
PlayerStateMachine.cs
public IEnumerator IJumpResetRoutine()
{
Debug.Log("Enter Routine");
yield return new WaitForSeconds(0.5f);
JumpCount = 0;
Debug.Log("Exit Routine");
}
}```
`PlayerJumpState`
```cs
public override void InitializeSubState()
{
Context.Animator.SetBool(Context.IsJumpHash, false);
if (Context.IsJumpPress)
{
Context.RequireNewJumpPress = true;
}
Context.CurrentJumpResetRoutine = Context.StartCoroutine(Context.IJumpResetRoutine());
}```
"Context" refers to variables back in the main state machine script
anyone know what it could be? 🤔
Context is a MonoBehaviour? Do you ever call StopCoroutine() anywhere? Context is also never disabled or destroyed? Also your code should be cleaned up, everything you access in there belongs to Context so why not move the entire method over to that class?
No, but I think I might have figured it out
I have a HandleJump that resets it on an enter state
but it seems my enterstate triggers after my InitializeSubState
so it start the routine and on the same frame setops it
i tried to make scrolling bg with tutorial, but this happens, what should i do?
!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.
Vector3.Dot or Vector3.SignedAngle
My colleagues absolutely despise use of Action feature
More specifically subscribe and unsubscribe feature...
Is there something I'm missing is it bad practice to use that?
hello, im making project with my friends. Its about simulating light in 2d(its for competition) and q of my friends is making mirrors another is making prism etc. And i have to do lens
but there are no tutorials for that
do you have any ideas how i could do it
for start i would like to make easiest len
and then other ones
get the normal and find the refracted ray by snell law
Ah right. I've just tried removing all of the path before "Resources" and I'm still getting the same result
i started with thin lens
including "Resources"?
Tried it that way too
Then there must've been additional issue.
So I tried:
Resources/Fonts & Materials/Futura Medium Test.mat
Fonts & Materials/Futura Medium Test.mat
How do you debug it?
if (textMaterial == null) { Debug.LogError("Material not loaded"); } else { Debug.Log("Material name: " + textMaterial.name); }
Directly after the Resource Load.
Regarding access to various components of a GameObject, most of the time I see people grabbing those in Awake/Start using GetComponent<T>().
I usually expose a SerializeField of the component types that I link in the inspector as it seems to me that it fits the dependency inversion principle and would be more robust.
Is there a common best practice between those two ? Any shortcomings I am missing for extensively referencing components via a SerializeField ?
Take a screenshot of the asset in that path with the path visible.
Is that actually a material?
Please, just go and read the docs
file extension huh
ye
Having it relative to the Resources folder and removing the file extension worked, thanks everyone.
Hi anywhere where i can send my script and ask for help finding my bug? i am genuinely at my wits end with this
just ask
Ok so i have a script that is supposed to spawn trees/flora randomly on a tilemap. It spawns them from higher y coordinates to low y coordinates to avoid tree sprites spawning on top of each other.
i have a gameObject[] of multiple tree sprites of which a random one is selected and spawned.
for some reason when i drag the same prefab into every slot in this list the spawning works fine.
But every time i try to select from a random of 3 prefabs they spawn on top of each other/ ones with lower y coordinates are sometimes spawned first.
All the prefabs are rendered in the same way and have the same pivot points. Why could this be the case?
Here my code: https://paste.ofcode.org/PzcWpnDhRVavaVZkpmU8Gq
!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.
my bad lemme just figure that out
show the screenshot of expected result and what you get now?
btw i think it should be the problem of sorting order
any opinions regarding this question please ?
They are essentially the same. The engine still needs to do work to link the serialized fields when runtime starts, but that IS marginally faster than using getcomponent (unless the getcomponent fails).
Drag and drop is not really dependency injection at all though
I would say there is a negligable difference between them, but I personally do GetComponent mostly because I like to code more than I like to use the inspector.
But generally drag and drop is preferred because of how easy it is, and it will not work if you do something wrong, whereas getcomponent will happily let you try something that won't work
i have a small question its basicly my first bigger code that hasnt been done with a tutorial / reference and i couldnt find any solutiong or cause of this.
i wanted to create if statements that have 2 conditions instead of just one but when i want to check if they are true by == it puts it out as a mistake in VS
Check your parentheses
you did if (Input.GetKey(KeyCode.LeftShift)) < this was the end of the if statement.
Everything you have after that is ???
aah so i need another () around the entire thing to clearify it belongs to the if statement ?
no...
you need to not end the parentheses before the rest of your condition
well it depends how you look at it. Basically an if statement needs to look like this:
if (something)
{
}```
what you have is this:
if (something) some random extra stuff;
{
}```
the semicolon is wrong too^
the whole expression needs to go inside the ()
i did what i thaught i understood and it went away i might have just explained what i ment wrong. dose this fix it ?
if ((Input.GetKey(KeyCode.LeftShift)) == true && (SprintMet > Sprintmin) == true)
{
Running = true;
CharackterSpeed = SprintSpeed;
}
it dosnt Line it with red anymore
if (Input.GetKey(KeyCode.LeftShift) && SprintMet > Sprintmin)
{
Running = true;
CharackterSpeed = SprintSpeed;
}
You could simplify it like this
aaah now i understand what you ment hmm now im confused why i had the extra brackets in the first place.
is there any use in having them the way they were like this (if it wasnt an Error)
if (Input.GetKey(KeyCode.LeftShift)) && SprintMet > Sprintmin
also ty for the help
ooo hold on no == check ? :0
== true is ALWAYS completely USELESS
This should have been an error. The parentheses for the if statement ends before the &&
And yeah, GetKey returns a bool, and the > operator returns a bool
if something is true, it's true.
bool x = true;
bool isXTrue = x == true; // you COULD do this but it's useless. Why not just do:
bool isXTrue = x; // x is ALREADY a true/false (boolean) value.```
== true is redundant, 100% of the time
Syntax of an if statement
if (this is the condition) this is the body
Thats good to know
Theres nothing really wrong with using an Action, its just one of many ways to handle events, regardless of what you use, youll still have to subscribe and unsubscribe from any event type, including a UnityEvent, in most cases, objects will have to manage when they (un)subscribe in their lifecycle (and events can have anonymous functions such as => ... or delegate { ... }, these cannot be unsubscribed easily unless the thing they subscribed to is destroyed and GC-collected before the object subscribing, AFAIK) - its often better to subscribe functions that match the event params anyway, so those functions can be unsubscribed (and easier to read imo), and you should always unsubscribe, as its possible to cause memory leaks if you manage events poorly, just as anything in programming can cause problems with poor management, though I think those are smaller problems depending on your project architecture
I would maybe ask them to elaborate, you can also ask them what alternatives/programming patterns they prefer over events, and the context in how they choose to structure code - events on their own is not a problem, but it also may not be a solution to every use case, depending on what is trying to be solved to begin with
PlayerController script - https://gdl.space/ewufofosac.cs
Battle Manager - https://gdl.space/oqokakaniq.cs
Enemy Battle Unit - https://gdl.space/kumovupoxu.cs
Character - https://gdl.space/demukuzami.cs
Character Base - https://gdl.space/busacifego.cs
Hey Guys! I apologize for all the code links, I am not 100% sure where my breakdown was. So this was working before when I had enemy object manually added into the scene but now i am trying to instantiate random enemies for an encounter. My attempted flow of logic is Player controller randomly generates enemies and passes it to the Battle Manager, I am getting a "Object reference not set to an instance of an object" error on line 70 in the Battle Manager when i load that script. Added screenshot of the enemy being added.
Based on that line:
newEnemy.name = newEnemy.GetComponent<EnemyBattleUnit>()._base.name + "_" + i;```
It seems pretty clear that whatever prefab `PlayerController.instance.enemiesToBattle[i]` was doesn't have the `EnemyBattleUnit` component attached to it
btw this line of code seems like something that should just happen inside EnemyBattleUnit. There's no need for an external script to be doing this.
Sorry that should read newEnemy.name = newEnemy.GetComponent<EnemyBattleUnit>().Character.Name + "_" + i;
except maybe for passing in the i variable
forgot i updated that after creating the gdl link
doesn't change my advice at all
although it's possible that Character is the thing that's null
you need to debug and find out
I believe it is what is null.
i guess what i'm not understanding is why its null, since there is a get; set; in Enemy battle unit for character
Where do you set it
that doesn't mean anything? That just means you created a property. You have to make sure the property is assigned to something.
it is
Okay, so it's set in Setup. What runs Setup
yeah i think thats my issue, the data passed to setup is supposed to be this new character
that enemiesInBattle gets this:
so i guess moving that line of code will just solve it maybe
So newEnemy is a brand new object that has never had Setup called
So it has no Character
@summer stump yeah thats also an issue i think, its being loaded on start
when the scene loads
I reread the code and think digi is right about the issue. newEnemy doesn't have setup called on it
It is added to a different list than the one you iterate it looks like
The commented line would be the right list.
But if SetUpBattle is in Awake, it would be called too early anyways
you need to call Setup right here when you spawn it
either that or stop trying to access Character right away
until after Setup runs
in fact you probably should just do that naming thing inside Setup
gotcha, ok i think i know what to do, I didn't catch that. this is my first game and i think i may have overreached a little for my skillset lol.
its definitely helping me learn alot but still feels a little overwhelming.
hi guys i have a question
here it suposted to appear Floor Tilemap, Wall Tilemap, Floor Tile and Wall top
the TilemapVisulaizer code its this
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class TilemapVisualizer : MonoBehaviour
{
[SerializeField]
private Tilemap floorTilemap, wallTilemap;
[SerializeField]
private TileBase floorTile, wallTop;
public void PaintFloorTiles(IEnumerable<Vector2Int> floorPositions)
{
PaintTiles(floorPositions, floorTilemap, floorTile);
}
private void PaintTiles(IEnumerable<Vector2Int> positions, Tilemap tilemap, TileBase tile)
{
foreach (var position in positions)
{
PaintSingleTile(tilemap, tile, position);
}
}
internal void PaintSingleBasicWall(Vector2Int position)
{
PaintSingleTile(wallTilemap, wallTop, position);
}
private void PaintSingleTile(Tilemap tilemap, TileBase tile, Vector2Int position)
{
var tilePosition = tilemap.WorldToCell((Vector3Int)position);
tilemap.SetTile(tilePosition, tile);
}
public void Clear()
{
floorTilemap.ClearAllTiles();
}
}
I need a simple help too
public class PauseInvoke : MonoBehaviour
{
public static PauseInvoke Instance;
public Canvas pauseCanvas;
private bool canvasStateChanged = false;
private void Awake()
{
if (Instance == null)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
private void Update()
{
if (Mathf.Approximately(Time.timeScale, 0f))
{
// Enable the PauseCanvas only if it hasn't been enabled before
if (pauseCanvas != null && !canvasStateChanged)
{
Debug.Log("Enabling PauseCanvas");
pauseCanvas.enabled = true;
canvasStateChanged = true;
Debug.Log("PauseCanvas enabled: " + pauseCanvas.enabled);
}
}
else
{
// Disable the PauseCanvas only if it hasn't been disabled before
if (pauseCanvas != null && canvasStateChanged)
{
Debug.Log("Disabling PauseCanvas");
pauseCanvas.enabled = false;
canvasStateChanged = false;
Debug.Log("PauseCanvas enabled: " + pauseCanvas.enabled);
}
}
}
}``` This code check if the game is paused the pauseCanvas pops up but the problem is that it prints out that pauseCanvas is enabled but the canvas is actually not enabled
I never faced this problem in previous unity project and its weird
@thick dew can you help me?
If it prints, it will be enabled, unless of course an exception is being thrown.
I will say this is a really weird way to do this though.
yea i was just trying to make it work across all scenes
A more robust approach would be to use an event or a static property on some kind of PauseManager
e.g. if (PauseManager.GameIsPaused)
I definitely wouldn't use Update.
regardless though none of that is related to your problem
I would guess some other code is disabling the thing later, or perhaps you are referencing the wrong object entirely
Since this thing is a DDOL singleton, is the pause menu itself ALSO a DDOL singleton?
You are referencing the canvas here: public Canvas pauseCanvas; but is that original reference still valid after the scene changes?
then presumably something else is disabling it again after
or you're incorrect about one of your assumptions/assertions here
oh why did i never thought of that
if the game is paused, it is before popping up pauseCanvas
!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.
When you define multiple elements in a single line, the attribute only applies to the first
You are the man, it is all but working, Only thing not loading is the sprites, which i don't think should have changed by adding this random element, all of the interactions are working, i can attack, take damage from the enemy objects.
its weird because that sprite is being assigned
That is just a download link for anyone on mobile
And I aint downloading anything, sorry
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class TilemapVisualizer : MonoBehaviour
{
[SerializeField]
private Tilemap floorTilemap, wallTilemap;
[SerializeField]
private TileBase floorTile, wallTop;
public void PaintFloorTiles(IEnumerable<Vector2Int> floorPositions)
{
PaintTiles(floorPositions, floorTilemap, floorTile);
}
private void PaintTiles(IEnumerable<Vector2Int> positions, Tilemap tilemap, TileBase tile)
{
foreach (var position in positions)
{
PaintSingleTile(tilemap, tile, position);
}
}
internal void PaintSingleBasicWall(Vector2Int position)
{
PaintSingleTile(wallTilemap, wallTop, position);
}
private void PaintSingleTile(Tilemap tilemap, TileBase tile, Vector2Int position)
{
var tilePosition = tilemap.WorldToCell((Vector3Int)position);
tilemap.SetTile(tilePosition, tile);
}
public void Clear()
{
floorTilemap.ClearAllTiles();
}
}
Did you read the bot?
all i can suggest is more debugging
add logs
Verify your assumptions. Check if the sprites are null, etc.
!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.
maybe editor bugs, try restart editor or have you saved the script?
it works on my machine anyway
It was sent you, and then linked again. This is the third time
#💻┃code-beginner message
Use a paste site
!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.
what do you mean?
I mean read the bot
Read what the post right above you says. Then follow the instructions
Is it possible to use check for a variable in a script and see if it is true in another script. like I have a bool touched in script A and I want to check if it is true in script B. Is that possible or am i going about this all wrong?
yes it's possible, and very common
go to one of that websites, paste your code in, and share the link to the code. It helps keep the chat clean instead of 100 lines
Ty
Yes, but click save before pasting the link here. The url will change
Because that is just a blank page
Also explain the issue when you get it
Oh, I think i finally understand your issue actually.
Make wallTilemap and wallTop their own lines
Not combined with floorTilemap and floorTile
not solved
Show what you have
You need the SerializeField attribute over the new lines
Did you save?
And do you have any errors in your console
yes
no
i really dont understand what is going on
ik this is unity but does anyone know anything about batch coding ?
whats the problem? i dont see where u assign the values for those variables in ur script anywher
ohhh
yes is that
try cs [SerializeField] private Tilemap floorTilemap, wallTilemap; [SerializeField] private TileBase floorTile, wallTop;
i try that dont solve
how can i solve that
there is compile error(s)
Fix the compile error
Clear the console and only compile errors will be left

When there are compilation errors unity may not be able to generate the necessary metadata for serialization as a result, the fields may not appear in the inspector.
That's what they originally had
And we just got them to change FROM that
really?
So, open up that file, look for the thing underlined in red and fix it
interesting, u dont see that often with beginners
haha!! just causing chaos!
They want separate references for each variable, which you can't do with that
Chaotic good haha
Digi said
#💻┃code-beginner message
I thought it was that both would have the same value, but I haven't tested
sorry im new and i have to do PAP its a final project to my course and I didn't teach anything about programming in Unity so I don't know anything
but be careful with Header or space since it will be applied to all fields...
👍
yea ill have to check into that... i would assume they both serialize the same way? hence tieing them together somehow, like in memory.. would still think u could assign different references to each, regardless of having a single attribute for both
yup, making editor scripts/ inspectors help ya work out how it works
feels similar to how markdown works
THIS IS AN ACTUAL ANSWER FOR THIS PROBLEM
.enable = true/false does not work
it should be like this instead: pauseCanvas.gameObject.SetActive(true);
this is ridiculous
because scale is 5x
check for billinear and rendering issues with camera
look in 2
where?
They do different things. .enabled is for components. SetActive is for GameObjects
no
please use Links, its hard to look at code this way on DC
!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.
how do i do that
I know i can have a script in the target itself to check if it collided but I was curious to see if it can be done that way
oh your enemy is not navmesh agent?
https://gdl.space/emanuvoniv.cpp i have this script to open a closet but for some reason the Debug.Log("a3"); is not showing tho the main camera colide with the object and idk why
interactable = true; this is not working too
idk what that is
2 is also scaled. Almost always keep it at 1
You want to zoom in with the camera, not scale it up
but does it have sth to do with the speed?
nvm you're in 2D
help if possible
first you def don't want to do this
WonderState rgb2d.MovePosition(rgb2d.position+movementDirection*Time.deltaTime*movementSpeed);
esp inside update
Rigidbody should be moved inside FixedUpdate
so the frame rendering is an issue?
wel the other is this
ChaseState rgb2d.MovePosition(rgb2d.position+movementDirection*Time.fixedDeltaTime*movementSpeed);
thats prob why its slower
well apparently this one is faster
you said
probably a framerate issue
and the number that gets multiplied by time.deltaTime
iirc its smaller
so it takes longer to get to moveSpeed
i will just check the c movementDirection*Time.fixedDeltaTime*movementSpeed
with debug log
if you debug.log both you def will get diff numbers
also should move both inside FixedUpdate
so they are both fixedDeltaTime
ok
ye fixedUpdate is more stable but the frame rate is kinda fixed
its a physics Update, ofc its fixed
physics needs consistency to work properly
i do i zoom it with the camera
I can call it game feature
i do i zoom with camera
show at 1
The type or namespace name 'Netcode' does not exist in the namespace 'Unity' (are you missing an assembly reference?)CS0234
what it mean by missing an assembly reference
Billy Butcher are you using an assembly definition?
if you don't know what a missing assembly is , should you be doing networking ?
Do you have the net code package installed? And if so does this error only appear in your code editor?
netcode != Netcode
yes
maybe need to put the reference in there?
guys someone said me this
"2 is also scaled. Almost always keep it at 1
You want to zoom in with the camera, not scale it up"
what can i do?

here right?
yeah
which one
Yes. You need to reference each assembly you plan to use. Why are you even using asmdefs if you are not familiar with what assemblies are?
all of theme will do the trick😁
I printed it the Chasing is around (0.01,0.00) while the Wandering is (0.00,0.00)
what the hell
Until you build and you run into further issues because the editor assemblies don't exist


hmm yeah but what did you print exactly ?
the movement vector per frame
i guess the frame rate is around 100
making the speed diff so much
i think i will stop using them for now til i know more about them
should I go with double cuz the number is too smoll
you mean this ?
var move = rgb2d.position+movementDirection*Time.fixedDeltaTime*movementSpeed
Debug.Log(move);`
no remove the rgb2d
nah i put myself to sleep now. Its 3 am and i am gonna call it a game feature

thanks for the help anyways
Ok good good.
what this mean?
Should just be an editor thing you dont need to worry about. You can restart if concerned
yea, nah im not bothered, im used to seeing worker[number] errors. but ive never seen the lifespan 4 frames... likely leak error
whenever i switch to different scene and then go back to the first scene the relay just stops
u have a good setup? im not familiar with relay or w/e but wouldn't u need to keep the logic in a scene that u always keep open?
persistence
ooor. initializing it when scene changes, idk tbh, maybe someone who does will chime in
irregardless maybe some snippets of your code/ pastebin link will help.. no ones gonna know specific's unless u share yours
oh yea that ^
you prob need to load it additively
Hi, Im trying to create a sprite from a Texture2D object that I load in with this function:
public void LoadTexture(string textureLocation)
{
Texture = Resources.Load<Texture2D>(textureLocation);
if(Texture == null)
{
Texture = Resources.Load<Texture2D>("Sprites/missingsprite");
Debug.Log("Couldnt find Texture2D at location: " + textureLocation);
}
Texture.filterMode = FilterMode.Point;
FrameCount = Texture.width / SpriteWidth;
}
Ive Already managed to make the texture less blurry, but now it looks like this:
How do I fix the colors?
Ive managed to fix it in the editor itself by changing the compression to none, but how do I do so programatically?
I guess for now I could also disable the 'Compress Textures on Import' setting in preferences, but ultimately Id like to be able to do it through a script as a safeguard
Why don't you just import it as a sprite directly in the editor
set all of the settings in the editor
and use Resources.Load<Sprite>?
void OnPreprocessTexture () {
var textureImporter = assetImporter as TextureImporter;
textureImporter.filterMode = FilterMode.Point;
//textureImporter.filterMode = FilterMode.Bilinear;
//textureImporter.filterMode = FilterMode.Trilinear;
textureImporter.textureCompression = TextureImporterCompression.Uncompressed;
//textureImporter.textureCompression = TextureImporterCompression.Compressed;
//textureImporter.textureCompression = TextureImporterCompression.CompressedLQ;
//textureImporter.textureCompression = TextureImporterCompression.CompressedHQ;
//textureImporter.spritePixelsPerUnit = 16;
textureImporter.spritePixelsPerUnit = 32;
//textureImporter.spritePixelsPerUnit = 64;
}```
How do I know wheter to akss in here or the -general version of here ?
Just ask in here
Despite several searchs and asking bots I can't figure out how to make an editor that will save to an external file that should be modifiable by the user and that isn't not a type of asset. I don't want that assets compiled as part of my project, just want to be able to serialize/deserialize it from the editor. I already know how to do that at runtime - but all the samples I find aren't "using UnityEditor" so I know they are not correct for editor-specific code. I can see there is a file manager available in the editor but unity musts also understand that the file isn't a random file it's the serialized version of a class in it
But I could also be completely wrong here and I should just accept that the "unity way" is textasset/scriptable object in the editor which get compiled as base recipes and user-modifiable recipes should only be loaded at runtime
Yeah thats what Im doing right now and it works well enough, so Ill leave it at that I think. Thanks!
You do not use anything in Unity for this. You use C#'s normal File system
Unity offers some utilities to help, like JSONUtility, to help convert some things to JSON format more easily.
but you're really using the standard C# File class
in the unity input system i have an input action and have it set to generate a c# class is there a way i can get a reference to the actions in the input actions through the inspector. Cause rn i have a script that i can attach to a button thats supposed to remap a key when its clicked to the next button the user clicks but i cant find a good way to reference the action it needs to remap for.
I see. Thanks a lot !
also if you see something called playerprefs, ignore it
it's a shitty unity solution for saving files
C#'s normal File system is the better and proper way to do it
I was hesitating between a textasset with a json in it, an external file, and a scriptableobject. I know that a scrioptable object would track references to other instances of the same type so that is a big advantage I let go but Id rather be able to edit the gamedata outside of unity
let me see if I can patch you something handy
where as with a json I'll have to keep numerical ids to tracks the links between items.
In this tutorial you'll learn how to save and read data into JSON files. We focuse more on lists which needs a little bit more code than default objects, but the latter one is also explained.
JSON files store data in key-value pairs and are mainly used in web languages for communication between client and server, but it is also quite useful for ...
this is a class that Velvary made to use the JSON utility better
it will help you serializing some things that are a little harder to serialize into a JSON
I make simple serializable classes with the bare minimum info that I absolutely need to reconstruct everything
thanks! Im comfortable with system.io normally in a windows app but everytime I use standard classes like this something goe s wrong in unity (last time was a wss server). SO I dunno I always feel confused and lost in unity with the serialization and wheter a standard lib like system.io will works the same or at all. I appreciate you giving me these ressources to look at. My bigegst problem is always "how to do things correctly in unity" 🙂
system.io is just normal C#
unity doesn't stop it from working
Unity just has some additional tools to help serialize some things that are a little more obnoxious to serialize
but anything you could do before, you can also do in Unity
i hope that makes sense
for my case, I have scriptable objects with unique string IDs. I save a simple class with a string for the SO. SO has a field for its unique string. And when I load, I use a dictionary (string => SO) to do the reverse
hey who can help me
idk wth but
some reason
when i put my code
and play
and when i go back
the half of the code is deleted
and i just started unity
You'll have to be a lot more specific, with screenshots etc. because that's not a thing that happens. Maybe you forgot to save your code? Or maybe you have your code in a Dropbox folder or something?
So even when reposting it to another channel you still couldn't get an entire thought out in a single line before hitting enter
it didnt fix it
lemme show
thats the code
when i reenter
(aka play and then reEnter)
and this is the code
- !code
- So what's the problem
📃 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.
!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.
Dunno if it helps I can see what the bot said twice
Seems that you dont see it or something ebt5 ?
im a dumbass
Because they sent the message again instead of reading it
So what is the problem
What is wrong with the code
i did explain u
i put da code
full of it
to the cs thing
then save it
and then
when i play it
Full thought, then hit enter
question does anyone know how to fix this? i accidently turn version control on but i turned it off and how i dont know how to fix this
hey real quick is there a way to mass change the name of a variable?
Your IDE seems to be set to a version you don't have installed
like change all mentions of it
yeah i have 2022 version how do i change it?
Yes, depends on your IDE but every IDE has a rename/refactor system
yes, every IDE has a renaming function
in visual studio community
!ide do the last bit where you change the settings in 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
• Other/None
right click it, rename
don't
speak
like this
it takes a
lot
of space
Make a full sentence, then send it
Yes after every other word. Complete a thought first, then submit.
does that also change it in other codes or just in the one i rename it
why is this giving me an error? this should normally work?
It would be pointless if it didn't
What does the error say
ty
alright thx
because you're using a nonexistent variable
musicSource does not exist. Perhaps you meant to refer to the variable created on line 6?
Okay and what is musicSource
So, i have a walking code, i putted in to the 2022 c# code and when, i press enter before saving it, and i wonder why it wont work because the player (bean) falls trough the floor, and when i go visit the code thing the most of it is gone (dont know why)
What do you mean "most of it is gone"
I think they mean the regions:
i putted in to the 2022 c# code
What?
bruh lemme just show a vid
yes, im trying to create a Ambience, which Plays in the Background. i use the Public AudioClip background1 to do that.
They are probably not used to regions and they think the code is gone because the #region is folded
unity 1st time
is this what u mean that your code is gone ?
give me 1 min
So use the variable created on line 6. You cannot refer to the non-existent variable named musicSource because you haven't created it anywhere
if i create one this happens:
yea
You cant just call a random .clip or .play on a random object it has to be the right type
object doesn't have a variable named .clip or a function called .Play()
Pretty sure you need to use the one on line 6, which is this one instead
if object type doesnt have a .clip property or .play method that will never works
sorry i have a really bad headache rn im not at my best rn, it all makes sense now
yea i misstyped it
sorry guys
works now
// cant wait to see what EBT5 meant
All i wanna do is move this game object to the position of the mouse in worldspace. I have the script attached to the GameObject and the GameObject in the scene. Why isn't it working?
Does this object have a CharacterController on it?
Those can interfere with teleporting via transform
Try logging mouseWorldPos before setting the position, see what it says in the console
soon done
Nothing was even printing to the console when I ran the game:/
are you sure this component is attached to an active object in the scene and is not disabled?
you need to start off by configuring your !IDE
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
• Other/None
The hell. Noise warning
That was messed up...
So you took the time to add in a stale meme to your video, but you did not take the time to expand the regions and see if the code is still there
(it is)
so it seems to be the regions like I thought. +1 for me yeah lol
Put so much effort into turning your request for support into a shitpost and so little effort into typing, reading, or trying anything on your own
No worries the same thing happened to me the first time I used c#
actually what do you place inside these parenthesis? Are you just supposed to leave them empty? I know you can put something in there, but what is it
boi
whatever parameters you want for the function, if any
Parameters your function accepts
i just mf started C#
I'm pretty sure that the GameObject is active. How would I even disable it?
Did you "just mf started" using a computer
instead of being "pretty sure" why don't you verify in play mode
There's a + box
mf
expand it
I'd start by understanding the code you copy/write, a #region is pretty much something that stands out in all this code
Don't use region blocks, simple as that
How does play mode help determine if it's active? Does it disappear out of the hierarchy or something?
hey guys how to i change my project unity version control to off im only working on my project by myself
Because if that's the case then it's not disabled
screenshot the entire editor window with that object selected so it is visible in the hierarchy and inspector
Version Control isn't necessarily for working with others. You DEFINITELY want it even when working by yourself
The selected Object is the one I'm having the issue with, and the script I posted earlier is the Tile Cursor Script
If you git a project and exercise a good commit discipline you can easily revert if you break something
i keep getting this error though
personally I .gitignore graphical assets but I guess unity 2022 does that by itself now
Can you show the full !code for TileCursorScript, including the class name and usings?
📃 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.
and have you looked at it in the Game view window?
that's not the same component you have attached to the object
I see big smilies and it's gone?
Welp serves me right for having similarly named scripts
thanks
hi, how can i pass gameobjects through scenes?
Whenever you unload a scene all GameObjects are destroyed in it. To save a GameObject from this you can:
- mark it as DDOL: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
- Move it to another scene which won't be unloaded: https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html
- Don't unload the other scene in the first place, i.e. load the new scene via additive scene loading.
No, not really, like everything new you need to !learn about it in order to enjoy it
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
and if i want to pass a vector?
Vectors are just structs
they have nothing to do with scenes
to pass them around between scripts you can use them as parameters in functions, or just access a Vector field/property from a reference
Ok so i have a script that is supposed to spawn trees/flora randomly on a tilemap. It spawns them from higher y coordinates to low y coordinates to avoid tree sprites spawning on top of each other.
i have a gameObject[] of multiple tree sprites of which a random one is selected and spawned.
for some reason when i drag the same prefab into every slot in this list the spawning works fine.
But every time i try to select from a random of 3 prefabs they spawn on top of each other/ ones with lower y coordinates are sometimes spawned first.
All the prefabs are rendered in the same way and have the same pivot points. Why could this be the case?
Here my code: https://paste.ofcode.org/PzcWpnDhRVavaVZkpmU8Gq
ty
you could also use a manager of some sort that you keep between scenes. The key is dontdestroyonload and getting a gameobject by name
But last I used uniity was unity 5 so I dont know really more than this
this happens between two different tree models, while 2 same tree models are fine
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I have a maybe dumb question. What situation can cause the behavior that OnApplicationFocus(bool focused /* this is always false */)? I've toyed with in-editor and out-of-editor, as well as clicking on the window vs alt-tabbing. Platform is PC.
Why do you keep repeating the bot commands instead of just reading them the first time they're linked to you
@spare sparrow you could add a sorting group component to the trees, and trees that are fine could be sorted above and other trees could be sorted to lower maybe? Haven't tried
What does a sorting group sort by? Does it change the order they are rendered in?
@spare sparrow yeah the render queue
you could even have them sort based on distance and other factors if you wanted
hmm. so i could make a list of all locations where a tree will spawn, then sort them by y coordinate and then render in that order?
I feel like the y sorting should already hide the tree
Couldnt I also just do that without the sorting group?
yeah
Is there anything a sorting group would improve with this approach?
check if the pivots are correct on each tree
they are the same on either sprite
and are sorted from the pivot and not center
wait how do you do that?
i think that might be the issue
on the spriterender itself
man i hate developin
i need to go back in roblox studio coding
:(
well time to switch to unreal engine
yeah cuz c++ is so much easier than c#...

damn, rly got my hopes up but it doesnt fix it
Hah, have fun with C++ mate if C# is too much you're in for some pain
and they are sorted by the same group?
wait but that shouldnt change anything since im not using a sorting group yet
no, im instancing them tile by tile, i might need to change the way i do that
sorting groups are for overriding sorting usually, but if all are not grouped then by default (group 0, layer 0) it's the depth of the pivot that sorts, or in the case of 2D isometric it's the higher up of the pivot on the y
well
bean wont move
when its player
but camere does
pog
i see, so the way i tried to sort the spawing "manually" in my code by sorting by y coordinate is a terrible way of doing it?
Have you done the learn.unity.com pathways yet?
Then I would presume you've put in code that moves the camera, but not any code that moves the player.
I last did unity in unity 5 and pluralsight test gaves me 6% so I dont remember almost anything 😦
okay
Oh, I'm not too sure what's your use case here, but without changing anything via script I just change my project's sorting axis in the settings then just sort all sprites by pivots and it works without having to deal with groups (beyond foreground and stuff that does need to be rendered first)
could you perhaps try complete sentences for once first
and can u shut ur mf ass mouth?
all I remember basically are the base concepts (prefabs, gameobjects, textassets, scriptable objects, components etc) but otherwise Im in a similar point as EBT5. TThat UI toolkit / ugui stuff is completely alien to me
No.
u grandpa looking ass hair
im watching a video rn, where the guy said the exact same thing, ima give that a shot
I've not tried the tilemap so there could be more related with it but that's beyond me
that fixes everything
This is my business. Hard to avoid reading your messages when they take up half the vertical space of the page because you type one word at a time
new sentence, just spawned
what exactly did i just do to fix it? what is this setting?
The sorting axis?
is it just "render stuff with lower y in front"?
nice!
by default is the depth that you sort by
and since i have no depth that doesnt work?
technically you do have depth since it is a 3D engine, but otherwise by default 2D you can treat z depth as another sorting group
That is in fact an artifical image. Sometimes called a cartoon, or an avatar. It is not their real hair...
i see
but since want more control over sorting in isometric you compare pivots from bottom to top to sort
makes sense
For my external recipes.json I have a very early storage class [System.Serializable] public class Recipe { /* edited for brevity */ public Sprite DisplaySprite; } //class because later we will add properties so struct isnt appropriate here . Im not sure it's a good idea to store a referency to a unity type like sprite like a scriptableobject would do. WOuld it be better to store the path to a a unity asset instead of that when I load it from an editorwindow or from the game I can find the sprite for it by path instead ?
game so pretty now, big W
what's those yellow line things?
the button is a placeholder for the car ?
I have no Idea how to convert a shader into URP compatible, is anyone able to help me?
this is a code related channel
hello guys, im new in unity and im doing a 2d game however im having a problem that i cant resolve for 2 days ahah. So i made a fov in my enemy with the transform, it has a mesh filter, mesh renderer a material and a script and attached it to a variable in my enemy object script. The fov(field of view) is visible however its behind the tilemap and i dont know why, i tried to change the ordering layer in runtime it did not work. Its visible outside the tilemap but not visible inside, if anyone can help me pls send msg or smth
probably want to correct your shader from crashing first
that pink thing its my fov, i want it to be visible
Have you tried adjusting the z-axis position of the mesh?
Mwshrenderers don't use 2D sorting
Iwas going to says that but it seems it's not so simple with 2d rendering and unity has this docs: https://docs.unity3d.com/Manual/2DSorting.html so I dont know what's correct between the two
that was a reply to Osteel
I haven't really worked with mesh and sprites simultaneously, so I don't know which is actually the correct approach 🫣
how can i change the Instantiated object between two gameobjects not randomly?
I'm not sure what you mean, like, choose between two objects to clone?
Instantiate(CanBeToggled, new Vector3(transform.position.x, -2, transform.position.z), transform.rotation);
I might need it myself for my rpg fief simulator game Im making when I draw a random map from the land use stats for a fief . Not an rpg I swear it's not an rpg if you send the adventurers to a dungeon instead of controlling them right? 😦 😢
so very interested in the discussion
Whichever object you pass to Instantiate will be the one that's cloned
but like, a variable in the place of the object, that can choose between two gameobjects
Yes
what variable can do that
Assuming you don't actually want any specific component from them, GameObject
and then i do something like:
gameobject = objectone;
Instantiate(gameobject, new Vector3(transform.position.x, -2, transform.position.z), transform.rotation);
?
If you already have a variable objectone use that
i have two variables for different objects
So pick one and pass it to Instantiate
i don't want to do that because the two variables were just and example, i have a bunch of them and im managing instantiating them by coroutines, i don't want to do a coroutine for each one for the sake of efficiency, so i want a way to have only one coroutine wich has an instantiate command that can be altered
How do you intend to decide which object to spawn
In the code, for each if/else it will toggle this variable
So, depending on the condition, spawn a different object
yes
That wasn't a question that was the answer
You have conditions you want to check to decide which one to use
so check them
i'm using coroutines mainly because of the yield return new waitforseconds() function, because there is a series of delays in the spawning process, by doing it directly in the if/else, the coroutine will be useless
at least i believe
Pass the variable to the coroutine
i will try doing a boolean brb
is pass a coding term or are you telling me to put the object variables onto the coroutine?
I am saying make your coroutine take in the object as a parameter
and pass that object to the coroutine when you start it
now that's full circle
i got it now
thanks dude
also thanks for the patience
https://gdl.space/tucawunozu.cs Hey guys, I am trying to figure out a way of preventing this object from duplicating, It is attached to my overworld scene, and will move from scene to scene with me, however when i return back to the overworld lines 31-35 are not executing, Could you think of a better way of looking for this? I would have thought this would have sufficed but it appears not.
is awake not called everytime this object is loaded?
Objects are only loaded once each
That is not what is happening.
Different loads are different instances
They are different objects
Different "this"
gotcha
It should just be else { Destroy(gameObject); return; }
If (human.needToPoo && human.atHome)
{
human.transform.position = Vector3.MoveToPosition(bathroom.transform.position.x, human.transform.position.y, bathroom.transform.position.z);
human.needToPoo = false;
} else if(human.needToPoo && !human.atHome)
{
human.poopInPants;
human.needtoPoo = false;
}
That certainly is some shit code
Perhaps keep it to yourself next time if you don't have a question
you need to be at least 13 to use discord
Mb I just wanted to share this deep philosophy with other fellow earthlings
Okay that worked, thanks homie
Hey my OnTriggerEnter on a hitbox is not working when I add a Force.Impulse that is too strong on the bullet. Is there any fix besides lowering the force?
For super fast projectiles, you probably want to use raycasts instead
I'm trying to get this OnDrop method to update my playercards array when I drop a card onto their spot. For some reason it is not updating in the inspector, any ideas?
im trying to set a certain "hover height" the car should be fixed at. currently the car sticks to the floor and rotates towards the racetrack, but it slowly goes down and doesnt stay at one height. does anyone know how i can fix that=?
Hello I'm new to 3d where can i find the "pixel light count" ??? I can't find it on Project Settings > Quality.
show code
!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.
well you're not doing anything at all to keep it at a fixed height so it's no wonder it's not staying at a fixed height
i was trying diefferent things which all didnt end up how i wanted
you can grab the normal from your raycast hit, multiply it by the hoverheight and that will be the direction and distance from the ground your object should be at
well if you know that is the direction and distance from the ground your object needs to be at, then put the object at the ground's position + that direction
Hello,
I'm trying to use Unity's "Player Input Manager" component, and I have it set to Join players when a button is pressed. I put my player prefab in there.
But when I spawn a player with the keyboard, and another with the Controller, both players are being controlled by both inputs.
Here's my script in case it's needed
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.
each of those spawned objects may have a different instance of your PlayerControls class, but they both use the same exact input bindings because you aren't doing anything at all to differentiate them
perhaps you want to check the docs pinned in #🖱️┃input-system for some information on how to set up local multiplayer input
I see, thank you for your assistance
Textmesh pro, also sorry for posting here I didn't know which one to use :3
Oh thank you 🙂
can someone tell me pls what does the color pink mean and why is there an if but green?
They are two different things
So two different colors
Btw you can change the color by some plugin in vs
ik but everytime i want to do the pink one it correct it into the green one
remove the Unity.VisualScripting using directive
there is a type called If in that namespace but you don't need anything from it
so i delete using Unity.VisualScripting; ?
yes, that's what remove the Unity.VisualScripting using directive means
then it sounds like your code is not inside of a method
it also consider the ifas a function
huh?
stop writing code outside of methods
yes that is not inside of any method
the only method in that class ends on line 18
so basiclly i cant use a condition outside of a method?
correct. how would that even work?
Cs is not python
you cannot write any code outside of a method that isn't a member declaration (variable, property, method, type)
if you are not familiar with writing c# code, then start with the beginner courses pinned in this channel
even more reason to learn the basics if you do not understand them
this shows you do not
the basic syntax of the language is literally the absolute beginning of what you need to learn
Is there some way to get multiple outputs from a function?
With my old unrealscript knowledge, I know that you could do something like this when building a function:
function bool FunctionName(int requiredInt, out int desiredOutput)
this function would return a bool, but would also provide "desiredOutput" to the function caller if they had that second parameter
caller:
myBool = FunctionName(funnyInt, someIntIWant);
Is there something similar in c#?
out or ref or pointer
out parameters exist in C# too, you just need to include the out keyword at the caller site as well as the declaration
Ah, ok
Out or tupples, that's your choice.
I'll probably use out. I've seen tuples tossed around here and there when modding games and haven't really figured out what they are
(int a, int b) tupple = (1, 2);
Basically just this.
they can be convenient, though i generally prefer just creating a small struct if i want to actually return multiple points of data
You can deconstruct it right after too.
The variables inside it will be used like any other variable.
(int a, int b) = (1, 2);
if (a > 0) do_whatever();
Because in this case, you're not allowed to refer to a. You can only do tupple.a. The names inside the tupple is just sugar and is equivalent to this (int, int) and you refer to each item by item1 or item2 by default.
is there a way to get every scriptable object created of a scriptable object class
Look into AssetDatabase methods
https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
Maybe something like that
I want to do animation on key press.. can anyone tell me how? (Like w key for run animation)
Use a Boolean parameter in your animator and flag it true when your key is pressed
However, if you're in 3D, you should be using a blend tree that is driven by something like speed.
Umm.. for it do I need to write a script?
Always
Where to attach
Doesn't matter, as long as you create a reference to your animator.
Let’s animate our character!
● Check out Skillshare: https://skl.sh/brackeys8
● Watch Player Movement: https://youtu.be/dwcT-Dch0bA
● Download the Project: https://bit.ly/2KK5AG8
● Character Controller: https://bit.ly/2MQAkmu
● Get the 2D Sprites: https://bit.ly/2KOkwjt
♥ Support Brackeys on Patreon: http://patreon.com/brackeys/
···········...
Should just try this series
I'm in 3d bro
shows the blend tree too
Ah, well the logic still applies but probably a 3D animator tutorial around
using UnityEngine;
public class AnimationController : MonoBehaviour
{
private Animator animator;
void Start()
{
animator = GetComponent<Animator>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.W))
{
animator.SetBool("IsRunning", true);
}
if (Input.GetKeyUp(KeyCode.W))
{
animator.SetBool("IsRunning", false);
}
}
}
I tried but not worked
In what way?
But no log errors also
What happens and what doesn't?
Does the bool get set to true and false?
Yeah
To true
@ivory bobcat can u guide me step by step to do animation on key press
Did you actually set the parameter on the transition to your running animation state?
Yeah
it says I dont have a reference but i do?
You don't, if it's saying that.
Make sure you don't have multiple scripts for example.
NRE won't show as an error in your code
it says its missing player stats manager
You need to look at line 56 of the player manager script
ah, may need to update the prefab. Actually, if it's already on the scene and you're using that one exactly it wouldnt matter now that I think about it
I cannot see any line numbers..
Something on line 56 is null
yeah the error says its the player stat manager
The error shouldn't say what but definitely something on that line
Likely that would be it though
it sazs it doesnt have it but it does
Try logging the variable
Just because it exists doesn't mean it's been referenced.
oh, it's networking too. Just do yourself a favor and update the prefab
wdym?
probably spawning a player manager with the last prefab instance
the screenshot is the prefab
the green + means it's not part of the prefab yet until you update it
what you have on the current gameobject is unique to it
how do i update it?
in the inspector panel at the top. I believe it's called override
May need to make another prefab and reference the model there
If you spawn another instance of player here, you're not getting those same scripts
nah, it looks like they are editing the prefab. it's just that the prefab includes a model prefab too and these objects are attached to that. but you cannot apply these overrides to a model prefab even though (annoyingly) the icon is there
there are 4 separate objects that could be null on line 56, you should either log them or use breakpoints to find out whihc are null
actually there are 3 not 4 because one of those objects is not null on a previous line
Debug.Log($"The Player Stats Manager: {playerStatsManager}", playerStatsManager);```
why not just Debug.Break instead of isPaused
That would pause at the end of the frame but it doesn't matter either way in this case, we'll just let it throw
What object in the scene is highlighted?
Was it highlighted yellow?
yeah
Try cs Debug.Log($"The Player Stats Manager: {playerStatsManager}", this);
Select the log after it shows
Something in the scene will become highlighted yellow
Check if the field is None
it hilights the player
where are you actually assigning to your playerStatsManager variable?
i think thats why
You can't use it unless you've assigned it something
Bro thankyou both so much!
whenever you see something is null, that should always be the first thing you check for
I always forget to call a function in update or assign a variabl in onAwake so i should be used to that by now
Thanks
I'm confused, using netcode for gameobjects, calling a serverRpc function but it errors on the client machine and just says only the server can spawn network objects but i though a serverRpc is run on the server/host [ServerRpc] void spawnPlayerManagerServerRpc(ulong clientID) { GameObject playerManager = Instantiate((GameObject)Resources.Load("PhotonPrefabs/PlayerManager"), Vector3.zero, Quaternion.identity); playerManager.GetComponent<NetworkObject>().SpawnWithOwnership(clientID); }
Hey everyone! I'm new to Unity and studying how Unity works!
I was trying to make my character move and this is my code:
public class NewMovement : MonoBehaviour
{
public float Move;
public float Speed = 10f;
public float jump = 100f;
private Rigidbody2D rb;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
Move = Input.GetAxis("Horizontal");
rb.velocity = new Vector2(Move * Speed, rb.velocity.y);
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector2(rb.velocity.x, jump * 10));
}
}
private void FixedUpdate()
{
}
}
the problem is my character keep sliding if I try to move both direction
!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.
Use charecter controller
understood sir!
what is character controller??
Just try it
Go to inspector and click add component and serach for charecter controller
roger!
@wide crown u can use charecter controller instead of basic rigidbody
It's much effective
And did it worked?
Thank you sir!
Just attach that component and attach this script
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public float jumpForce = 10f;
public float gravity = -9.81f;
public Transform groundCheck;
public float groundDistance = 0.4f;
private CharacterController controller;
private Vector3 velocity;
private bool isGrounded;
void Start()
{
controller = GetComponent<CharacterController>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, ~0); // Checking all layers
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f; // Reset gravity when grounded to prevent accumulating downward force
}
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 move = transform.right * horizontal + transform.forward * vertical;
controller.Move(move * moveSpeed * Time.deltaTime);
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
Now I have given comments also
there're a lot of of things to catch up tho
Yeah
Or just fix your rigidbody controller
@nimble scaffold They are using Rigidbody2D so you cant swap CharacterController for it..
yes it did!
no, Thanks!
For sparing your time with me
I did try to use the new input system but it was complicated
Bye @wide crown
Gud bye
why this medthod crash my game?
So finally tell did charecter controller worked?
my colliders all 2d
Then forget about CC
Does it crash of freeze it?
freeze
@wide crown
why??
An infinite loop then
It is for 3D
its because of lerp?
so I have to figure out how to fix my code then
But it did work right?
Yeah. You're probably using lerp incorrectly. Does "rate" change from 0 to 1?
but that was some useful information
i set my rate to 0.01
Well, then do the math. Theoretically, your transform scale would never get to the target.
Also, I don't see a point in a loop like that at all. It would be the same as just setting the scale to the target value.
i want to make it shrinking over time
What exactly does this mean?
Does it keep moving sideways normally, when you would like it to stop instead?
If I move right, while holding down "right" I also press "left" my character slide to the right
the opposite direction is the same
Well, that's not gonna do it then. Code runs line by line, so your while loop would execute all the iterations immediately.
oh right i see now
Do you have a cheap keyboard?
Looks like you are just using "Horizontal" axis directly so there is not much that you could do wrong
no sir, It wasn't the keyboard
letme show u
Send mp4
understood
Mkv does not embed
