#đ»âcode-beginner
1 messages · Page 171 of 1
Why would you want to wait 2 seconds for nothing after it? Coroutines are used when you need to delay an action
but dosn't it just wait at the end before restarting the cycle?
read the link I sent you and learn?
i did
Then surely you can answer your own question
hello, im trying to make a bool called alive set to false from the component "PlayerMovement", when the int player health reach 0 from the component "PlayerHealth" but it doesnt work, any help ?
start is not a thing
dont tell me it was this simple 
damn it did not correct it?
the problem was the error pointed at the update function and i kept changing everything there only to notice me forgeting to make the s capital
Ah the joys of programming âš
can someone help with this
Have u configured your ide yet, as the message below yours tells you to
I doubt many people are gonna sit there and watch a 2 minute video to help you. If you can summarize your issue it's better to just show it all in one concise message instead. (And delete this message where you reply to one message then link 2 others)
It works perfectly thanks @slender nymph and @rocky canyon for your help, i appreciate it a lot, thanks fr
i tried that at first, but ill go again:
Animation wont stop playing, even when its boolean parameter is set to false.. thats it actually, but i checked and tried so many things, but no luck
Simple question: how do I get a reference to an image?
is there a way to link objects such that if I make a change to one, it makes a change to all?
drag ur image into the image box
make child
Is there an error in ur script? It may not update the inspector until it can build
would that include changes like changing the sprite of a tile
i guess so i never tried, i only tried with 3d gameobject not 2d one
No, the inspector is updated correctly
What that do
It is just not managing any reference to the Image class
did u drag the image in the box
Image2 which wants an image isnât shown in your inspector view that you screenshotted, image is not an image object so wonât allow an image in it
That box is only showing the GameObject named "image" I need to assing an actual Image since I want to change the color

I only made that gameObject to show that it is not showing as expected
Your IDE will have autocomplete, highlighting, but most importantly will tell you errors
does it let you drag it in
No because itâs the wrong object type
Oh ok
Man, I can drag in a GAMEOBJECT, I want to drag an IMAGE
so she might need to change the type
or
wait no
So why are you defining image as a game object, define it as an Image in the code
exactly that's what is confusing
it should say image
did u save your script
Like image2, but that isnât in your screenshot which is why Iâm asking if you have compiler errors or havenât saved etc
I AM NOT DEFINING THE IMAGE AS A GAMEOBJECT, IS ONLY TO SHOW THAT THE REFERENCE TO THE GAMEOBJECT WORKS WHILE TO THE IMAGE DOESN'T
Calm down Iâve literally said thatâs what youâre doing and I donât know why youâre doing that
DIDYOU SAVE YOUR SCRIPT
I use caps so none misses it, I am not mad :p
I did
you're probably using the wrong Image type
also chill tf out
No itâs not showing in his inspector apparently? No idea since the information heâs giving is useless though
do u want to use it as a UI
right because they are using the wrong Image type
I think his issue is that image (game object) shows in inspector but image2 (image) doesnât? His naming makes it very confusing
Yeah thatâs what I said then they did all caps
@frigid sequoia what do you want to use it for
hello, so i have this spawner but the problem is if i set the prefap as a reference it will only follow my player first position but if i make the reference as an object in the hierarchy it will constantly follow the player but if i destroyed the original referance i get an error, any help?
There, that's the actual code I am using, I only did the last one to make it clearer, but apparently did the opposite
The image List is not showing
what do you want to use the image for?
Nor can I get the reference through code
UI?
Am I calling it wrong?
You should not be using UIElements
Try adding [SerializeField] before public (and replace public to private)
You are not using it in practice, so it shouldn't be in your code
what is your image type?
Did it before, doesn't do anything
this is not going to fix their issue because they are literally using the wrong Image type. they are using the UIElements Image
That shouldn't matter for this
it need to be sprite2d and ui
Yeah I just saw theyâre using wrong imports
It would be like Image.sprite right
This image
Except that it does.
No, I have some experience with coding and unity, but i dont think its that good with unity
exactly finnally someone that says that
@frigid sequoia ?
Thatâs not their issue, the issue is the code, it needs to import UnityEngine.UI not UIELEMENTS
I am concerned that the code apparently compiles, because it really shouldn't
What does it do?
i mean she did not show what was her image type
If I am calling a reference that I am not using shouldn't do anything
Doesnât matter
Itâs not showing in the inspector
Sprite
The actual image they wanna put in doesnât affect the code not showing the field in inspector
You are using it though, Image is also in UIElements
considering they have the UIElements namespace imported but not UnityEngine.UI we can clearly tell which Image they are using
GetComponent has no generic constraints
Oh, I suppose it's a... yeah
Then what the heck should I be calling?
Change UIELEMENTS to UI
pls..
Thank u
have you used the debugger to step through your code and figure out where your logic is going wrong yet?
If you want to make improvements to the code I suggest just taking out FindGameObjectsWithTag and just add the reference to the player on the enemies
Why does that work though? Like I don't undertand
Thank this guy
because UnityEngine.UIElements.Image is not the same thing as UnityEngine.UI.Image
You were referencing this type https://docs.unity3d.com/ScriptReference/UIElements.Image.html
God it's gonna be good when UGUI gets thrown to the fire
I literally didn't reference anything, it just added it automatically
But why is that the default?
you need to pay more attention to the namespace it shows when you are autocompleting types
Like wtf?
It isnât, you wouldâve been given two options
There is no default
yes, even when the boolean parameter for the animation is false, or if i straight up set it to false, the abimation STILL plays
Also, there is nothing wrong with UIElements, I am using it and not using UGUI
i got no clue where to go fro mthere
what does findgameobjectwithtag have to do with that ? it just counts the number of enemies that are present so it spawns mor e
Still, if I am calling an Image from Elements, how come that it doesn't show in the inspector?
UIElements' VisualElements are not serializable by Unity. They are not scene objects, or configurable via the inspector.
do note that i am not referring to just watching the bool parameters in the animator window. since those aren't actually being used for transitions and it's purely your own logic in your code that determines what animation to start playing. you need to step through your code and figure out where your logic is going wrong
You can have a spawner class that keeps a list of enemy references and when one dies then you know the spawn a new one instead of checking the scene every update to see if an enemy exists.
- Confirm your code is actually running
i did and i cant pin point where it goes wrong
could you explain a little more please ?
isnt that just using a prefab ? when i use enemy prefab i cant fill the follow target with the hierarchy player i gotta use the prefab player and if i use the prefab player they just go to my spawn instead of follow me
Use the debugger or logs
the cluster is the enemies spawned by a prefab while the one following me is from the hierarchy
Inspector -> set is Trigger = true ;
ok so, if both the enemy and player exists on the scene then you should be able to drag the player object reference into the follow target component on your hierarchy
the problem you're having is setting the prefab data of the enemy to follow the player prefab instance which does not exist in the scene as of yet (it's just a template of data which you instantiate later into the game)
so if you want to spawn enemies dynamically, you need a runtime way to figure out what target there is to chase on the scene
but i tried without the prefab and if it died it gives me this error
Ignoring what I said previously about using FindGameObjectsWithTags, you can use this to find the player reference too if you choose to do it that way
I usually avoid those methods because it requires searching throughout the scene hierarchy, but you're better off having a manager component/singleton/static ref to grab the current player reference.
using System.Collections.Generic;
using UnityEngine;
public class RandomSpawns : MonoBehaviour
{
public GameObject[] animalPrefabs;
private float spawnRangeX = 10;
private float spawnPosZ = 10;
// Start is called before the first frame update
void Start()
{
// Makes it so it spawns randomly at xx speed
InvokeRepeating("SpawnAnimal", 2, 1.2f);
}
// Update is called once per frame
void Update()
{
}
void spawnAnimalLeft()
{
// Pulls the element from Prefabs
int animalIndexLeft = Random.Range(3, 4);
// Randomizes the position
Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
}
void SpawnAnimal()
{
// Pulls the element from Prefabs
int animalIndex = Random.Range(0, animalPrefabs.Length);
// Randomizes the position
Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
// Randomizes the position
Vector3 spawnPos1 = new Vector3 (10, 0, Random.Range(2.0f, 12.0f));
// Spawns the animals
Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);
}
}
Following the official unity tutorial, my 3 and 4 prefabs spawns on random X coords even though I wrote 10.
{
// Pulls the element from Prefabs
int animalIndexLeft = Random.Range(3, 4);
// Randomizes the position
Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
}```
--
```Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));```
Please link to large codeblocks !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.
Also, SpawnAnimal uses spawnPos not spawnPos1, which you just don't use in that method at all. spawnAnimalLeft is never called.
asked a few people but no one's been able to solve it yet,
my purpose: when unit is clicked, highlight should appear
my problem: that doesn't happen.
i drew around the issue in red.
it's definitely in the red i drew cuz i made debug logs for other parts of the code like the raycasting and that worked fine
EDIT: no debug log message appears in console when i click on unit
any help would be appreciated ive been on this for a while now
You're not calling SpawnAnimalLeft at all here, indeed
there's 2 of them
ah saw it, 1 second
void spawnAnimalLeft()
{
// Pulls the element from Prefabs
int animalIndexLeft = Random.Range(3, 4);
// Randomizes the position
Vector3 spawnPos1 = new Vector3(10, 0, Random.Range(2.0f, 12.0f));
Instantiate(animalPrefabs[animalIndexLeft], spawnPos1, animalPrefabs[animalIndexLeft].transform.rotation);
}
void SpawnAnimal()
{
// Pulls the element from Prefabs
int animalIndex = Random.Range(0, animalPrefabs.Length);
// Randomizes the position
Vector3 spawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), 0, spawnPosZ);
// Randomizes the position
// Spawns the animals
Instantiate(animalPrefabs[animalIndex], spawnPos, animalPrefabs[animalIndex].transform.rotation);
}
}
``` am i on the right track
Actually I think I did this by creating several methods for each posible edge of spawn, working exactly the same but with different range of possible coordinates and used another Random to decide which one should be called when some enemy should be spawned
If you want it to spawn at a constant X position, this won't do it, you still choose a random X for spawnPos
And as far as I can see, void spawnAnimalLeft() is still left unused
You only schedule the execution of SpawnAnimal() in Start()
I'm trying to programatically generate an inventory grid, but all of the sprites are generated with a scale of 240. The object holding the generation script has a scale of 1, 1, 1
I know this will generate all sockets in the same place currently, I'm trying to solve the scale problem first
(Instantiate has an overload that sets the parent, you don't need to do it in two steps)
{
// Makes it so it spawns randomly at xx speed
InvokeRepeating("SpawnAnimal", 2, 1.2f);
InvokeRepeating("SpawnAnimalLeft", 2, 1.2f);
}```
i am so lost
how so?
Your function isn't called SpawnAnimalLeft
The name is different. Yours has a lowercase "s"
Consider using nameof(spawnAnimalLeft) instead of a string - gives you additional safety as the compiler checks that what you pass in nameof actually exists
You should define the exact types you are working with because GameObject is pretty ambiguous.
Is it UI? Is it SpriteRenderers? Who knows
- Don't
- Respond with "wdym", "?", or "didn't work" without justification.
I have zero clue what you didn't understand about my simple sentence.
I might as well just repeat myself for all I know
int animalIndex = Random.Range(0, 2);
(0 , 2) shouldn't include these first 3?
ty
oh so it should be 0, 3?
Yes. But why not use the whole list here?
apologies. My intended question was, do you know the syntax to set the parent within the Instantiate() function?
I found the section of the docs that concerned my question
I think the max in the range is exclusive precisely to work with Lists
Random.Range(0, animalPrefabs.Length)
because i no no wanna :'(
--
because i have 2 different spawn codes where one of them spawns animals from top of the screen while the other is from the left
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Look at the docs for the overload that sets the parent.
Or use your IDE's autocomplete and just look at the arguments
i couldnt have thought any other way to do it tbh
If there's two different use cases, wouldn't it make more sense to have two lists
Two lists/arrays?
Easier to manage if you suddenly want to add another element, and want it to spawn without altering the code at all
Ask in #đ±âmobile where it's relevant. I see you did, in that case, don't cross-post.
I'm trying to find any other way to refer to my image. The gameObject is an Image object, from GameObject > UI > Image
but anything I try is read as not a valid name
Image
the type or namespace is not found
Then include the namespace
Is your IDE configured?
It should suggest things as you type
Also, it's not "The gameObject is an Image object", it's a GameObject that has an Image Component on it
Do you have the namespace
I see, thank you
and give you namespace suggestions if you get errors regarding namespaces
it successfully autoincluded EventSystems earlier
no, fixing
Guys, I know this question is kinda abstract, but how do IEnumerators work?
idk if this is code related but why my canon ball just fall of
Any class that implements these properties and methods
My error is now that the object I want to instantiate is null
So make it not be null
Like... I want it to do a fade out effect on a image over a given time; but I nerver undestand the logic of Enumerators
coroutines are mini update loops
Like, what should I place in the if? I have been stuck there for a while now XD
If you mean coroutines, they are ordinary functions all the way until they hit a yield instruction. They'll then wait for however long that condition specifies (with a WaitForSeconds or a WaitUntil or the like, with the default value of null being "next frame"), then pick up right where they left off
This does nothing https://unity.huh.how/coroutines/waiting
You should be using a loop with similar logic to this (however not to do with Vector3) https://unity.huh.how/lerp/coroutines
If you are getting an error saying this Instantiate is the one with the error, then there exists a mainInvInstancer without a socketPrefab set
But it is executed only ONCE, just that you can stop it temporarily with wait for seconds?
Yes
Yes, once you start it, it runs straight through, pausing at any yield instruction it finds
It runs once per call, and each yield is just a place for the state machine to continue from next Update/(other time)
That wasn't it, but toggling the mainInvRoot object on and off in the editor while the game was running fixed it for some reason
Your error is on Start. Toggling it wouldn't "fix" it, the error already happened
Start doesn't run again when the object is disabled
then there'll be plenty of time for someone to see it and respond to it
Cool, well it's not relevant here, and you shouldn't cross-post. So don't
https://paste.ofcode.org/34QC4T8vtaVGy5x7gRDLqKQ
This works just fine (the way i want it to be at least), thank you guys for ur help â€ïž
You aren't getting the point: don't cross-post, and don't argue about it
correction, I disabled the object, ran the game, then enabled it in scene view while the game was running.
Then wait like everyone else
people who care about mobile look into mobile, if nobody looks into mobile, nobody cares about mobile and consequently your mobile problem, that wont change if you put your problem into other channels.
Also generic gradle errors are impossible to debug without diving into the project with someone. Who has that time?
yes, you need to actually read the error messages and do some research
Imo someone should just make a site like mine specifically for gradle errors
surely they're all solved problems
I just don't give two shits about mobile so 100% could not be bothered đ
dealing with mobile in your free time is a special kind of masochism đ
says I have 0 errors in the code đ
Just to be clear, I want the given image to Fade from the initial Alpha to 0 over the given time; and I want to be able to stop this process with StopCouritine from other methods
That's a good thing. If your IDE is configured you can now ask because it's a requirement to get help here
Are you using rigidBody?
yeah
In the ball?
yeah
And you want it to collide with a surface with a collider?
clearly pls
Should work with just that
oh ye
If you are using external methods to move stuff, just as Translate in code, it will always clip through
Since it is not using physics
hold on
followed a tutorial to make the mesh deform when the ray hits the mesh, the input side is working but this deforming code isn't and idk why since I followed the tutorial
it uses physics
If you are moving all with physic and you have rigidBody it should collide with all colliders that are not set to be trigger colliders. Have you double checked everything?
it's supposed to shoot with rigidbody
the problem is that idk if it's my computer who loads while it's shooting or if it's a problem
Is it possible to make a sprite look different from 2 different cameras? For example I have 2 players playing chess so their views are from 2 different sides One of the players boards looks correct while the other all of the sprites for the pieces are upsidedown any idea on how to correct this from the camera view or will I have to do something else?
Is it like sprites in 3d space?
Im making a 2d chess game I might not understand what your asking but let me know if this answers it I have a 8x8 board with tile objects that have sprites attached that show the pieces and when they move the sprites get cleared and put where they need to be. I was just looking to see if I could change the visual through 2 different cameras to be rotated 180 degrees so both views look correct.
I guess the same thing would work for the move previews to only show it on the side that is actually moving aswell
hi guys does anyone know what this green plus means in the highlight for the playercommander? the playercommander is a unity asset and the cube is just a 3d object i created
the + indicates that you've added an object to a prefab instance
notice that PlayerCommander has a blue box next to it
A solid blue box is a prefab.
A blue box with a stripe on top is a prefab from an asset (oftentimes a model)
Unity tracks all of the changes you've made to the prefab instance. You can apply them to the prefab or revert them if you want.
for example, I've attached two spot lights to this model
ah okay that makes a lot of sense, appreciate it
Overridden properties will show up as bold and get a blue line next to them in the inspector
er, at least they get a blue line. maybe i'm just imagining the boldness
I assume that's an online game?
Online games usually handle clients the same way regardless of what side they're on. You would only have 1 camera for the local client and only adjust the player specific data, like the pieces colors.
how can I change directional light color at runtime?
I tried this didn't work
Lights[1].color = Color.Lerp(new Color(117, 229, 255), new Color(60, 117, 202), foglerp);
{
hungerSlider.maxValue = amountToBeFed;
hungerSlider.value = 0;
hungerSlider.fillRect.gameObject.SetActive(false);
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}```
check lerp as well
Your colors are wrong
you're using color
They take floats in the 0..1 range
i literally have 0 idea what i have done till now (followed the .pdf, just wanted to see how would it look)
Color32 is what ur looking to do
hungerSlider is not assigned
I'd just calculate the correct values and use Color, but you could definitely use Color32 if you want to keep the 0-255 values
or GameManager cant be found.. unsure tbh
color32 is more performant afaik
it's going to get turned straight back into a Color
is it ? hm weird they recommend Set/GetColor32 but turn into floats for color
I tried this still not working
Lights[1].color = Color32.Lerp(new Color32(117, 229, 255, 255), new Color32(60, 117, 202, 255), foglerp);
show the whole context of this line
Lights[] is an array of directional lights
foglerp is a float
running this in update
foglerp += Time.deltaTime * lerpSpeed;
Lights[1].color = Color32.Lerp(new Color32(117, 229, 255, 255), new Color32(60, 117, 202, 255), foglerp);
Can you see if the color changes on the light components?
This is not really wrong though. Assuming they start at 0.
And does the code execute? Can you debug the fogLerp value?
even at 0 it would "work" but its still wrong way to do it
They add to it over time. I don't see a problem.
the problem is with the type it says connot implicity convert type 'UnityEngine.Color32' to 'UnityEngine.Experimental.GlobalIllumination.LinearColor' so it isn't compiling
You referenced wrong type then
Ok, so, it's not "not work", it's a freaking compile errors. Please mention that first...
sorry đ
This is weird though. What type are Lights?
Directional Light
I mean in code...
Can you share the whole script?
!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.
Seems like it
You should use UnityEngine.Light instead.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
okay đ
I'd also remove these 2 lines to be safe:
using Unity.VisualScripting;
using UnityEngine.Experimental.GlobalIllumination;
thanks
does anyone know how to create a good isometric char controller
Create a normal character controller and just angle the camera 
Sorry for off topic but I was looking for this emoji for 10 years! Where did you get it??
Yeah, that lol
Oh. I see. I thought it was among the standard set or the unity server one.
Thanks!
Maybe we can add it đ
lol, that'd be the new hotness for sure đ
did that, how do I polish it? because the camera keeps turning when the player does, and I want it to stay in one spot relative to the player
Use Cinemachine to do that
It can't.
obviously my method of changing the camera rotation is just wrong so I'm asking for an alternative
i thought it'd be the same as changing camera position
if only
Rotation != Position
so what do I do
* Quaternion.Euler(0, 90, 0);
alr thanks
unity courses messing me up lmao
this is the 2nd course where they're like "okay fix these bugs we wont tell you how to do it"
which is fine because we learnt everything before
except for changing camera rotation in C# theres nothing about that yet so im left in the dark
im not even gonna ask what a Quarternion or Euler is, i know its some complex math shi
unless you could explain it in simple terms
Euler is something you should probably know already, unless you are very young
nah it wasn't part of our curriculum
cause nationally we're stupid
i'm 17 btw got a B as my final maths grade so yknow not bad
never heard of Eulers
I would suggest just using angle axis for stuff like the camera, but it's probably fine if you want to use euler. It's just when you're doing more rotation other than a single axis does euler become a little janky
The xyz axis rotation is called euler angles
Euler angles is 3 angles, 90 degree is an angle for example.
Quaternions are how Unity actually represents rotation
(Euler angles are named after a mathematician Leonhard Euler)
Same one as the mathematical constant E aka Eulers number
alright this makes a lil more sense to me
it's more relevant in like college algebra
good thing I didn't take that đ
my friend took maths, additional maths and further maths
what the hell was he thinking
he's hating life rn
I'm trying to smooth my player's movement but SmoothDamp() doesn't seem to be working correctly, I must be doing something wrong.
I'm trying to make the smoothing take a second, but it ends up taking around 7 seconds. Any idea why?
private float smoothedX = 0f;
private float smoothedZ = 0f;
private float smoothVelocityX = 0f;
private float smoothVelocityZ = 0f;
void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
smoothedX = Mathf.SmoothDamp(smoothedX, x, ref smoothVelocityX, 1f);
smoothedZ = Mathf.SmoothDamp(smoothedZ, z, ref smoothVelocityZ, 1f);
}```
i made a canon and if i want to rotate it, should i do it with GetKey input and then i use transform.rotate or is there an other way to do so
If you're just rotating left and right as long as the key is held down, then that sounds reasonable.
If you want to limit the rotation, I'd suggest this...
[SerializeField] Quaternion leftLimit;
[SerializeField] Quatenrion rightLimit;
[SerializeField] float turnRate;
void Update() {
if (Input.GetKey(KeyCode.A))
transform.rotation = Quaternion.RotateTowards(transform.rotation, leftLimit, Time.deltaTime * turnRate);
if (Input.GetKey(KeyCode.D))
transform.rotation = Quaternion.RotateTowards(transform.rotation, rightLimit, Time.deltaTime * turnRate);
}
This will rotate towards the leftLimit or rightLimit rotations by turnRate degrees per second.
I find this to be a lot more reliable than messing with euler angles
you constantly get footgunned by how they wrap around
oki these unity courses have got me on a good path so far
i'm pretty happy now
just wanted to say that :D
I must warn you, it sadly gets way less exciting in the middle point
Still you learn a lot and it is cool, just not as engaging I would say
Can I have some help with my code I'm makeing a flappy bird games and I've got a error and know idea what it could be
I don't say this to discourage you, quite the opposite; I want you to know that the same happened to me and I pushed on and I don't regret it in the slightest, just don't give up đ
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
You can use !code to share your 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.
-= is an opperation, not a declaration, you cannot initialize the value like that
You are telling it to subtract from something that doesn't exist
Is there anyway to fix it
Remove the -
You would need to do the subtraction inside a method
You tried to do it in what's called the initializer
Which is not allowed
ok i will see but it's better with no limit, more fun
and easier
Omds I'm so stupid I've only been codeing since today and didn't realise I put that there
Mb
I think you don't even need to use the = 0 at all, a primitive value is 0 by default
Fields are initialized with their default value.
And indeed, for int, default is 0
(default is, literally, the default value for a given type)
local variables are not initialized automatically, so you do have to give an explicit value
That's actually quite weird honestly
Is there any reason for that?
Probably because it would require an enormous amount of...
public Foo whatever = null;
You can't reason about whether a field will be assigned before it's used because you can use an instance of the class well after it's created
vs. a local variable, which you explicitly create and then use
So it would try to initialize all values even though the process path doesn't need them at all...
The compiler needs to be able to prove definite assignment before a variable is used
Gotcha
it would demand that you initialize all of them, because that's the only way it could prove definite assignment
so fields are just initialized automatically to cut down on pointless initializers
that's my interpretation, at least
Is it possible to swap a CapsuleCollider2D between horizontal and vertical with a script?
Sure, if it's a property on the component, you can change it in script.
Never tried before, but seemingly yes. just use .direction
Somehow completely overlooked that while staring at the documentation lmao
Preciate it fellas
Anychance anyone know how to fix this
maybe
How
!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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
MagicđȘ
read your errors
@long lantern
using Random = UnityEngine.Random will resolve the ambiguity if you can't remove System
Otherwise you can qualify the Random by writing UnityEngine.Random.Range
But as you were told before, don't take photos of your screen. That should really go without saying...
na my camera just ass
Well there's ways to not have to use it
I'm making a shapeshifting system. This system will have both a regular human form and a shapeshift form. However, the shapeshift form will have more than one type, while the human has only one. I want to know a simple way I can check what form the shapeshift is. I was thinking of using bools, but am not sure how in this case or if there is a better variable type to use.
I'd say make a bool to check if you're shapeshifted, assuming there's much a human form can do that all shapeshift forms can't do, and then considering how many forms you may have, you can always check upon the type, or enum if you want to keep shapeshift as a single class.
The OOP way would be design a bunch of method implementations like Jump(), Dash(), ect, that all forms would implement and just call them when you do those specific action regardless of your type. Even if some types could not dash, you'd still call them with a minimal implementation.
Hi, so I found I'm running into a common issue, my script is finding an object that is destroyed on next update. Seen a lot of people with similar issues on stackoverflow, but how do you actually get the findObject to be delayed by one update()? One vaguely mentioned it can be done with a bool?
Sounds like you should just check your objects beforehand before you access them
check for what? is there a 'to be destroyed' flag that gets added or something?
Oh, so I forgot to add that these other forms just have different values. Lets say there is a light and heavy shapeshift form. They both do the same, but have different values.
Well, you can do it two ways. One would be to add a flag or disable the object and check against those flags, or resolve the issue in which your methods do not break if these objects are destroyed in the next frame, such as checking nulls and retargeting as an example.
The OOP way would be ideal then if you wanna design with abstraction implementations then, because if the behavioral methods is the same then you can call them by their base type, but a single shapeshift class could work too if you just wanna swap out stat/damage profiles
oh wait so does the object become null once it actually is destroyed even if findObject got its reference?
Calling destroy only queues the object to be destroyed but doesn't happen to till end of frame, and after that frame if you try to access it you'll get a null ref exception, so checking nulls is ideal when you're dealing with volatile data like enemies. (but it's always better to just object pool them anyway)
okay thank you! yeah I think that pretty well solves it. If I understand correctly, I just check for null and if it turns up null I just call findObject again to get the new instantiated object
Yeah, exactly. Just run the method again if needed, but ideally in the next frame and not in a while
{
Destroy(currentHole);
yield return new WaitForSeconds(0.5f);
Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
Instantiate(hole, PM.dungeonSpawns[Random.Range(0, 9)].transform.position + PM.currentRoom.transform.position, Quaternion.identity);
EH.treeSpawnCount -= 1;
Destroy(gameObject);
}``` ok this spawns in some gameobjects at spawnlocations pre set out however it chooses them randomly what i want to do is adter the first gameobject has instantiated i want that spawn to not be able to get chosen in the next instantiate
how would i go about doing that
It's generally easiest if you shuffle the array and then just iterate over it
Here's a pure c# implementation of creating and randomizing an array
public static void Shuffle<T>(this IList<T> list, int start = 0)
{
int count = list.Count;
for (int i = start; i < count - 1; i++)
{
int j = UnityEngine.Random.Range(i, count);
(list[i], list[j]) = (list[j], list[i]);
}
}
It's my first time using . I am trying to make bools with them, is that possible?
Make bools with what?
void ManageType() {
if (shapeShiftType.light) {
}
}
public enum shapeShiftType {
light,
heavy,
dark
}``` This code I want to use similar to a bool.
It will check if the type is light, dark, or heavy. <- How can I achieve this?
Use the compare (==) operator or a switch for enums
the (==) looks to be some sort of int. Is there not a way to make it true or false?
You would compare this to a value, the same way you do already with any other data type like int.
int number = 0;
...
if (number == whatever)
you are missing an object of type shapeShiftType
== is the equality operator that checks if two things are the same (value/ref)
what you're trying to do right now is like
if(0)
Where it would check whatever is left and right of the equality operator
Are you saying to use a structure with the ints? Like 0 = a shapeshift type, 1 = another?
i am saying right now you dont have any object of type shapeShiftType. There are just values defined for type shapeShiftType.
If myLight == shapeShiftType.dark
it was dark
enums are just named integral types, starting from 0, in your case light = 0, heavy = 1, and dark = 2.
So your if statement if (shapeShiftType.light) { is basically just if(0) {
Declare an instance of shapeShiftType so you can set it to any of those values, and compare it against the one you're checking for
This? cs [SerializeField] shapeShiftType currentType;
That'll do it
yes now you can compare that to being light, heavy, dark
So all I can do is check if it is 0, 1, 2, etc.
Or rather switch (myLight) case shapeShiftType.light: ... break; case shapeShiftType.heavy: ... break; ... etc
functionally, sure, but they're now named
I'll have to learn cases then. Thanks for the help!
what's the best way to make an openable/closable door for a very simple 3d game? Using hinge components, an animation, using code, what?
Your gonna have to use code for any method
With a hinge you would get a more physicsy type of door you can push. Animation would be probably be easier to set up
Just one animation for opening and then play it in reverse for closing
Is there a way to make this easy to change? I know that there isn't a stats variable. I am asking how I can make one that functions like a overall stat ```cs
case 0:
turretStats = LightTurret.stats;
break;
public class LightTurret : TurretStats{
public float hp = regular;
public float dmg = low;
public float moveSpeed = veryFast;
public float jumpForce = strong;
}
Is this pseudo code ?
Explain what you want to do without code. Like what is the actual functionality you want to happen in game
I am trying to make a turret that can change types (e.g. dark, light, heavy, etc). These types have different float values. All I need is a way to change the regular turret stats into the type turret stats.
So, like, you want to have pre defined "light" "normal", etc. values that you can swap between?
Correct!
Probably the best way to do this is to create an enum for the different types, and then for each variable instead of having a single float, make it a list or array. Then you can cast the enum to int and use it as an index to the list
So "light" is 0, "medium" is 1, "heavy" is 2, etc.
Maybe a list of predefined SOs for stats?
And enums are just integers under the hood, they count up in order. So if you just define them in some order and keep that same order when you write your lists you can use a named enum as an index
If you don't want to worry about ordering it, a dictionary is fine too
you can reverse an animation? Is there an option to do that in the animator?
iirc you need to set the speed to -1
apparently unity does not support dynamic even in mono ;-;
error CS0656: Missing compiler required member 'Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo.Create'
Like steve said just set the speed to -1
This is your brain on DOTS đ€Ł
Hello, I'm not sure if this question belongs here as I'm not sure if it involves changing code or not.
I have an avatar ready to be uploaded, but there's one more animation I want to it.
However, when importing the animation file, I get errors and I believe it's saying the scripts for the animations are trying to run from dynamic bones, when the avatar uses physbones. Is there a way to update/change the script so it will use the physbones instead?
Thank you!
None of this is built-in Unity, it sounds like !vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
uploading an avatar, physbones, dynamic bones... these are all non-standard things
Ok, sorry.
oh nice, tysm
Ill check that out
how do i adjust the position of a tmp_text
Several methods here
https://docs.unity3d.com/ScriptReference/RectTransform.html
i was trynna use transform.position lol
guys as there is no one active in #đ»âunity-talk im posting it here... sorry but please try to say
what to put here?
this isnt a code question, doesnt matter if others arent active in another channel
where tf are my log files
my log files are created when running in unity editor
but if i build then run manually no log files get created
I have a script Script1 that has line "public Script2 script2" inside it (which I drag in the Script2 on script1's inspector to make it work)
and then I have a THIRD class Script3 that has a "public Script1 script1" line inside of it (which I drag in Script1 on script3's inspector), and is trying to do:
script1.script2.score = 1
but the error log says Object reference not set to an instance of the object.
what would you do in Script3 to fix this error? i can post actual code if this is described too confusingly
Why are bullet collisions so inconsistent here?
ok i got it working
turns out i had an uncaught exception
[ now : 17:41:8:359] [ since last : 0:0:0:19 ] CAUGHT EXCEPTION while initializing ScriptManager : System.IO.FileNotFoundException: Could not find a part of the path "C:\Users\small\Game Engine Projects\Unity Projects\Flow - Unity 2023\Build\Net21\netstandard.dll".
first you need to determine what is actually null, script1 or script1.script2
post the bullet script
Because fast moving rigid bodies dont make good bullets
yeah may just wanna use raycasting
rigidbody is actually decent at highspeed stuff, but you may need to add some additional logic
(at least better than my methods)
I'm making the character be able to dash, but when the character in the air, the character dashed really short. I hooked up a Debug.Log to monitor the dashVelocity variable, but it turned out to be identical even when in the mid air.
This is the code handling the Dash methods
https://gdl.space/ajanucicof.cpp
About the character suddenly dashes backward, this is expected because I want the character to dash backward when the horizontal input is not performed
you only set the velocity once in the script but it's still being changed throughout the coroutine, no?
actually not too sure, but log throughout the duration if you havent
Probably won't work but just in case try resetting velocity to zero before applying dash velocity on rigidbody?
how do you fix issues like this with cubemaps?
welp i ran a full release build and dynamic and non-dynamic are both signifigantly faster
bool use_dynamic = true;
if (use_dynamic) {
Debug.Log("obtaining class instance");
if (instantiate_class(compileInfo, "Main", out var instance)) {
Debug.Log("obtained class instance");
dynamic i = instance.instance;
actionQueue.Enqueue(() => i.onStart(obj, 1));
actionQueue.Enqueue(() => i.onStart(obj, 2));
actionQueue.Enqueue(() => i.onStart2(obj, 3));
actionQueue.Enqueue(() => i.onStart2(obj, 4));
} else {
Debug.Log("failed to obtain class instance");
}
} else {
{
if (sm.obtain_callback_direct<Runnable<GameObject, int>>(out var del)) {
actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 1));
actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 2));
actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 3));
actionQueue.Enqueue(() => del(compileInfo, "Main", "onStart", obj, 4));
}
}
}
compared to just running it in the Unity Editor
Yeah that didn't work :)))
Makes sense.
Debug all the way xD
```cpp
int2 pixelCoord = int2(id.xy);
float2 uv = float2(pixelCoord)/cubemap_res;
float PI = 3.1415926535;
float3 position = calcPosition(uv, tbn);
float2 long_lat = longlat(position);
float2 sampleUv = float2(
(long_lat.x + PI) / (2.0 * PI),
(long_lat.y + PI / 2.0) / PI
);
float radius = cos(abs(long_lat.y));
float distortion = 1.0 / max(radius, 0.0001); // Avoid division by zero
float level = log2(distortion);
float lowlevel = floor(level+1.0);
float local = fract(level);
float3 color = (textureLod(equirectTexture, sampleUv, level).xyz)*(1.0-local)
+(textureLod(equirectTexture, sampleUv, lowlevel).xyz*local);
that's my calculation to make up for the stretching but that does not seem to be working, why is that so?
That's the worse part of it, I might say. I really don't know how to utilize the debug feature :))
Everytime I look at the debug, my brain cooks itself and die :))
You just print whatever data you want to see and confirm it's same as what is expected to be at the time
I did use Debug.Log to print out the dashVelocity.
The weird thing that is the both on ground and mid air dash gave me the same results.
For example at line 16 you would print Debug.Log(Dashvelocity);
To see if it matches the expected calue
They gave me the expected value. But the travel distant in the air is much shorter than on the ground.
how do you get rid of distortion in a cubemap?
My animation only plays once. Anyone know why that could be? My code for the animation is pretty simple
click the animation in asset
there will be a loop check
make sure its checked
@west sonnet
doesnt seem to toggle and is constainly on. not sure if thats the correct componenet
isn't there literally a error
how can I fix my cubemap looking like this that' s the map I'm unwrapping onto my cubemap
why are shadows doing this even ingame can someone tell me how to fix it?
@zealous atlas @gilded verge This is a code channel
it's a math issue
well, take it to advance with some actual math then instead of assuming we know it by the image
link where i should send.
@slender nymph that issue is had with OnMouseEnter/Exit fixed itself randomly just when i was about to ask my lecturer about it :/
Didn't change anything at all and it just started working properly
could've just been an editor bug đ€·ââïž
Kind of upset that I can't find out what the issue was but I guess its better that it's fixed
I rebuilt the project on a new unity version as well which works fine so it was all a waste of my time đ
I did learn how to use pointerevents tho so thats good
hi, i wanted to knwo why i can't drop the TMP Text i created in the slot of the function (it even says that the type is mismatch, anyone knwo why?)
public class InventorItem : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler,IPointerDownHandler,IPointerUpHandler
{
// item Trashable
public bool isTrashable;
//Item Info UI
private GameObject itemInfoUI;
public TextMeshProUGUI itemInfoUI_itemName;
public TextMeshProUGUI itemInfoUI_itemDescription;
public TextMeshProUGUI itemInfoUI_itemFonctionaliter;
public string thisName, thisDescription, thisFonctionaliter;
//Consommer
private GameObject itemPendingConsumption;
public bool isConsumable;
public float healthEffect;
public float caloryEffect;
public float HydratationEffect;
// Start is called before the first frame update
void Start()
{
itemInfoUI = InventorySystem.Instance.ItemInfoUI;
itemInfoUI_itemName = itemInfoUI.transform.Find("ItemName").transform.Find("Nom").GetComponent<TextMeshProUGUI>();
itemInfoUI_itemDescription = itemInfoUI.transform.Find("ItemDescription").transform.Find("Description").GetComponent<TextMeshProUGUI>();
itemInfoUI_itemFonctionaliter = itemInfoUI.transform.Find("ItemFonctionaliter").transform.Find("Fonctionaliter").GetComponent<TextMeshProUGUI>();
}
public void OnPointerEnter(PointerEventData eventData)
{
itemInfoUI.SetActive(true);
itemInfoUI_itemName.text = thisName;
itemInfoUI_itemDescription.text = thisDescription;
itemInfoUI_itemFonctionaliter.text = thisFonctionaliter;
}
public void OnPointerExit(PointerEventData eventData)
{
itemInfoUI.SetActive(false);
}```
are you sure you are using a TextMeshProUGUI object? and if you are certain that is the type of object you are dragging in, are you certain that you are not trying to drag a scene object into a prefab?
Is that even a "beginner" issue lmao
it's just them posting a #archived-shaders issue in #đ»âcode-beginner again despite having been told probably dozens of times now that shader issues belong in the shaders channel
well the one i try to dragged to it, i created by doing right click - UI - Text TextMeshPro , so it must be a tmp Text no ? because i did that before and it worked perfectly
you can literally just look at the component to confirm. but yes that would most likely be a TextMeshProUGUI object
so now we move on to the second part of my message, are you dragging a scene object into a prefab
yes
that is the entire issue then.
https://unity.huh.how/references/prefabs-referencing-components
i dragged into prefab asset
yeah 2 years beginner
Looks to me like you are treating it as a 360 panorama, but the image you are using isn't a panoramic image
thanks that makes a lot of sense, so I can't use a eqirectangular texture as a skybox?
A 360 will be warped on the top and bottom, example here:
https://spectrum.ieee.org/media-library/a-360-degree-panoramic-simulation-of-the-lunar-surface-used-by-the-researchers-to-represent-terrain-similar-to-that-of-the-moon.jpg?id=25586717
We ain't HR bro, 2 years isn't "beginner" 
You can for sure, there are different types of cubmap settings
oh so I have to use a different projection?
I think so, I'm just waking up in honesty, so my brains a touch fuzzy... I'm having a hard time finding a good reference for you
I know unity out of the box handles a bunch of different projection types. And that they can be used for skyboxes. The bottom image in your example looked like it was more meant for a UV sphere or something therein
But the visual looked like it's trying to draw it as a 360, so it squishes the top and bottom
hm yes so following things are happening
I have a equirectangular map
then a shader writes to each face of the cubemap using longitude and latitude but the pixels get dispatched for each pixel on the cubemap
I'm putting a lot of projectiles on the screen at once and am looking for a good solution to this. The projectiles can't be replaced by raycasts as they are slower moving objects.
Should I still put a rigidbody on these and move them through its velocity, or is there a better way to do this? The projectiles will have colliders on them and not necessarily always move on a straight line.
define a lot
not a lot, use rigidody
What do you consider the upper limit for rigidbody to be?
depends on your target platform, but generally < 100 for mobile or WebGL
I do need a rigidbody on objects that are supposed to physically collide, right?
As opposed to just registering "hits"
only if they move
you need a rigidbody on one or both of the collidee and collidor
Why am I getting a null reference exception in ``` private void MoveToCursor()
{
// Trace a ray from the camera to the mouse position
mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
bool hasHit = Physics.Raycast(mouseRay, out hit);
// Move to the mouse position
if (hasHit)
{
agent.SetDestination(hit.point);
}
}``` in the line with `Camera.main.ScreenPointToRay`? Like, I assume it's because the reference to the `Camera` is null, but shouldn't `Camera.main` automatically be assigned to my `Camera` Game Object?
So bullets that bounce off walls for example
I could have a rigidbody on the bullet but don't need one for the wall
a collider is enough?
yes, or the other way round
physics system moves things while respecting collidions by moving the rigidbodies during physics step
if you have an obj with collider, no rigidbody, and doesnât move, then it will be fine
You can put a breakpoint and step through this and you'll see exactly where the null is
The documentation says that it uses the "The first enabled Camera component that is tagged "MainCamera" (Read Only)", but how do I access this tag?
I'm pretty sure it's in Camera.main
I'm just wondering how to make sure Camera.main accesses my scene's camera
Unity tags if you've not used them yet
oh.
is Camera.main null?
Yep, I just checked. It's there. Perhaps I'm stupid âïž đș
Thanks guys lmao
i just put a singleton on my main camera for other reasons
About singletons. What would be the best approach? Every "main" script for an object I want to singleton-fy should include a singleton pattern or should I have a "singleton script" with nothing but the singleton pattern that I drop into whichever object I want to make a singleton?
object pools, game managers, level managers
vfx managers (basically another object pool), load/save manager
databases; items, enemies, npcs (scriptableobject lookup)
i donât make objects singletons. I make scripts that should be singletons, and put them on objects that should be unique. Because almost every unique object would be getting unique code
Yes yes I know. What I'm asking if I should have the whole awake singleton thing on every single one of these scripts, or if I should have 1 script with only the singleton pattern that I drag into these objects
oh ok !
like, if i make a CameraController that moves the camera, that should be a singleton
i should never have 2 instances fighting over the camera
then obviously, CameraController would be on the Cameraâs object
I also have a singleton called WorldObjectReferences, that just stores serialized fields as references to unique gameobjects that lack code.
Things like the starting position and goal flag
The second suggestion is more related to another type of pattern (service locator and other subsets of it) where you'd have a singleton with a list of keys (like local players from a networking singleton) that defines these specific implementations.
This way you wouldn't have a single camera singleton, but if you grab a player key then you can refer to that specific one. Another type is similar to gameobject component searching where the key reference is composed of different types not known at compile time.
Are there any suggestions on dealing with the collision of the door, using an animator, it would still retain collision and push the player aside in order to open, unless some fancy tricks used in code would stop the animation when it touches the player
Can any one help, my problem is that i can see trough the wall, i cant pass the wall but i can see trough it, i dont want to see trough the wall.
mess with the near clipping plane on the camera
tysm
Well what do you want the door to do when it touches a player ?
Can you show the player model and where the cam is positioned on said model?
Stop I guess. It's a bit janky in hdrp 2021
i downloaded a free asset on unity
But that might just be becuz of the character controller?
Well check for a collision with the player and stop the animation
Can you show it and where the cam is positioned on it
Okie doke ty
alterantively, increase the radius of the player collider
either way will work
When I want to test my game in Unity without clicking on the object containing my code, my code does not work. What could be the reason for this?
show !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 none of that is code. but have you considered fixing your errors?
Could these errors be the cause of my problem?
probably, but i literally have no way of knowing becuse you didn't bother sharing any relevant code. but you should start by fixing the actual errors in your console before attempting to fix any potential logic issues
I will write to you after correcting the errors, thank you.
Hey, I am working with wheel colliders to try and get a bike going... I'd say technically... the bike works and drives... but as part of my degree I have a physical bike here which sends data to my game...
In said data there is a km/h (m/s) value - so... I am trying to accelerate the bike to said value... (I don't wanna go into it rn as of to why, I can later though)...
So my problem is... when increasing torque/... the bike only accelerates to about 1.3m/s (and not the 8.3m/s that I am currently trying to test)
Even when increasing the torque to "yes" it stays at around 1.3... maybe gets a bit higher... but I can't accelerate/decelerate in a manner that makes sense... and I am deeply lost...
has anyone maybe an idea what to do? I watched some tutorials and yes read through documentation... but I can't get it running.
Anyone perhaps has a minute to help me?
thats the torque I try to apply to the wheel...
but it seems to "slip" even when I crank up friction...
just lerp the alpha channel on its color to 0 and back to 1
hello
how do i control player's terminal speed if i use addforce with forcemode.force
Terminal velocity is a product of your drag.
However, I'm guessing you don't want to have to fine-tune drag to get the exact velocity you want.
you can also just clamp the magnitude of your velocity after applying force if you want finer control over the maximum possible velocity
An alternative is to just reduce the amount of force you apply if it's in the same direction as your velocity
That's a good idea. I mostly just use ClampMagnitude but that seems like a much more physically accurate solution
yea ... simple solutions are best for me i guess
hello im encountering a problem that i am not familliar on my unity. im trying to make a 2D game but when i started to try my code, it isn't working. i already have a terrain and it also have a collider even the character. why is that?
owo that... could actually work
tysm fen
show !code and actually describe what you mean by "isn't working"
đ 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.
Send the code
there's no problem in the code. it's just simple im just trying to make the character to jump. wait ill show the code
can you not drag a child class script to a parent class list in inspector
you can
you can drag a GameObject with a child class script attached to it to a field which is expecting a reference to an instance of the parent class.
sorry how to use it
wouldnt that be a list of gameobjects then
no
Getting a Kernel at index0 is invalid although there are no errors?
this means you have either dragged in something that is the wrong type or you are trying to drag a scene object into a prefab
fix it
i did what u said XD, i dragged a gameobject filled with the child script to parent list
You should show the code and then show exactly what you dragged and where you dragged it
here's a rough idea:
// cut force by by 0% at slowdownStart and by 100% at maxSpeed
float speedFactor = Mathf.InverseLerp(slowdownStart, maxSpeed, rb.velocity.magnitude);
Vector3 desiredMove = // get this from player input
float alignment = Vector3.Dot(desiredMove.normalized, rb.velocity.normalized); // 1 when aligned, -1 when opposite directions
float alignmentFactor = Mathf.InverseLerp(1, 0, alignment); // 0% when aligned, 100% at 90 degrees or more
float forceMultiplier = Mathf.Lerp(1, alignmentFactor, speedFactor); // as speedFactor rises, we care more and more about which way the plyaer is trying to move
this only happens when you assigned something and then changed the type of the list or the thing later.
@tight saffron
hey sorry to bother again but by what scale should i reduce force
also i am adding force while i hold the button to make player move ,how exactly is it supposed to work?
It feels a bit rough to me
i don't like the variable names
Rigidbody.AddForce should be called every FixedUpdate. It tells the rigidbody how hard it's being pushed
i think this is what u wanted? im not sure
i dragged a gameobject with a card child in it towards the database and there's that
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("escape"))
{
GetComponent<Rigidbody2D>().velocity = new Vector3.(0, 14, 0);
}
}
}
you were not dragging a a "child object" into that field
here, im just trying to make the character jump but it isnt working
you dragged a scene object into an asset's field
hold on
the component is already at my character and not on the ground
start by making sure that your !IDE is configured so that you can see where your compile error is
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
If that's the exact code you're using then you need to fix your compile error
i dragged a gameobject with the child script in it xD
confusion 1000
If this game object a prefab, or is it an object in a scene?
Assets can't reference scene objects.
is the gameobject in a scene or was it a prefab? because assets (like scriptable objects) cannot reference in-scene objects except for at runtime (when you pass the reference via code)
my bad
It's the same reason prefabs can't reference scene objects. Prefabs are assets.
Sounds like you want to make that card into a prefab.
and then, presumably, use the card database to store all your card prefabs so you can spawn them
use DoTween
you can fade in/out/chain things in seconds
DoTween.DoFade(desiredValue, duratin)
if you don't understand how if and else statements work i'd recommend going through some basic c# courses like the ones pinned in this channel
no wonder my console was sketchy all the time on past projects, if only my teacher taught me this
because it legitimately worked without error as in it accepted the instance and console was not having it
i think that my ide is configured
screenshot it
First you check if alpha is greater than or equal to 0. Then the enclosing statement checks if it's equal to 0
Your first statement subtracts alpha if it is equal, so the second if statement won't be true
Also, don't check for equality with a float . . .
so you didn't even copy the code correctly then
oh i changed it i forgot
anyway, use a keycode instead of the string for your Input.GetKeyDown
https://docs.unity3d.com/ScriptReference/KeyCode.html
and pay attention to the console when you try pressing the key
when you use a string with GetKeyDown, the compiler cannot help you if you type the name wrong -- all it cares is that you gave it a string
when use a KeyCode, you must type a correct name from the KeyCode enum, like KeyCode.Escape -- if you use an invalid name, you get a compile error
Does someone knows how to get rid of that problem?
do people even read warning/errors anymore..
just remove this from your object and move on
Ok wasn't thinking i can just remove it
I have a Serializable class named "Stink". When i create without "readonly" keyword, it works fine. But with readonly, i get null exceptions. How can i avoid that?
Works
private Stink stink = new ();
Not works
private readonly Stink stink = new();
i get null exceptions
Where do you get exceptions?
Show the code that throws the exception and the full exception
actually I think it makes sense. When unity tries to replace your instance with the serialized instance, it won't be able to because you marked it as readonly
remove readonly to avoid that.
hello
you can't make a serialized field readonly, the Unity Engine needs to be able to write to it.
i have a issue
this is how it seen at first and then it becomes that when i run the game
But initializing an object with new() keyword shouldn't avoid that?
character falls and then this happens
When unity deserializes the serialized object, it needs to write to the field
where is the code question?
there is no code right now its only a character rigidbody2D box Colliders and Bones
This channel is for code questions. Also this just looks like fully expected ragdoll behavior? It's hard to tell without knowing what you want to be happening
oh im sorry
Consider adding what you expect to be happening when you ask this in #đ»âunity-talk since it's not code related
when you drop a ragdoll on the ground, it does that, no?
its like there is multiple characters
when it hits the floor
its like motion blur đ
That's because you have this
Ah, the "Completed Solitaire" effect, that's what the issue was
I didn't even think to check that
Hello, I'm using Input Manager for a project and when I use use it for joysticks, my character is going forward by default as if the joystick was held up, but it's in its neutral position. Does anyone know how to fix it ?
Hello guys, can you help me with this. I don't know where the error could be. The list (screenshot 1) should include "PlayGame0" and "QuitGame 0", but they are not there. screenshot 2 - code (making a menu for the game)
you need to fix your compile errors and get your !IDE configured đ
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
can somebody tell me why this isnt working for the movement
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
âą Visual Studio (Installed via Unity Hub)
âą Visual Studio (Installed manually)
Fix your VS first
_movevector always 0y 0x.
void Awake()
{
_rb = gameObject.GetComponent<Rigidbody>();
_controls = new PlayerControls();
}
void OnEnable()
{
_controls.Enable();
_controls.PlayerControl.Movement.performed += OnMovementPerformed;
_controls.PlayerControl.Movement.canceled += OnMovementCancelled;
}
private void OnMovementPerformed(InputAction.CallbackContext context)
{
_moveVector = context.ReadValue<Vector2>();
}
Also for some reason cant see serialized fields in editor?
[SerializeField] private const float PlayerSpeed = 5f;
[SerializeField] private const float UpwardForce = 10f;
Im using unity input system
I would say you can't see those fields because they're const .. but I haven't tried that before, I'm assuming
yeah const wouldn't be serialized because they cannot change at runtime
Yeah changed that now I can
But why input sistem not working?
I did it how person in the guide did but my vector is always 0.0
if it works for them, but not you, you did not do it how they did - you've missed something or done something wrong
show your full code, including how you determine it is always 0,0
It did not help
what didn't help? fixing your compile errors? because that will fix the issue
Im determining it with debug LogWarning
Thats just showing me move Vector
On left is guide, on right is mine
again, show the full !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.
public class PlayerController : MonoBehaviour
{
[SerializeField] private float PlayerSpeed = 5f;
[SerializeField] private float UpwardForce = 10f;
private Rigidbody _rb;
private Vector2 _moveVector = Vector2.zero;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
private PlayerControls _controls;
void Awake()
{
_rb = gameObject.GetComponent<Rigidbody>();
_controls = new PlayerControls();
}
void FixedUpdate()
{
if (_moveVector.y > 0) // Checks if movement is up and there is no upward velocity.
{
// I wanted jump to feel like jump instead of movement.
if (Mathf.Abs(_rb.velocity.y) > 0.1f) return;
_rb.AddForce(Vector3.up * UpwardForce, ForceMode.Impulse);
}
else
{
var movement = PlayerSpeed * Time.deltaTime * new Vector2(_moveVector.x, _moveVector.y);
transform.Translate(movement, Space.Self);
}
Debug.LogWarning($"Movement: {_moveVector.y} {_moveVector.x}");
}
void OnEnable()
{
_controls.Enable();
_controls.PlayerControl.Movement.performed += OnMovementPerformed;
_controls.PlayerControl.Movement.canceled += OnMovementCancelled;
}
void OnDisable()
{
_controls.PlayerControl.Movement.performed -= OnMovementPerformed;
_controls.PlayerControl.Movement.canceled -= OnMovementCancelled;
_controls.Disable();
}
private void OnMovementPerformed(InputAction.CallbackContext context)
{
_moveVector = context.ReadValue<Vector2>();
}
private void OnMovementCancelled(InputAction.CallbackContext context)
{
_moveVector = Vector2.zero;
}
/**/
}```
đ 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.
You also have to setup the actions assets (or whatever they're called) correctly
why do you have a hold interaction on your Movement action
They added on default
try removing it
because with it you have to hold the input for whatever the duration is set to for it to invoke the performed event
I'm trying to follow a tutorial for grid based inventory but using touch controls instead of mouse. No matter where I place the anchor for the grid, the code always treats the center of the coordinate system as the bottom-right corner of the screen.
do you actually have the input system enabled in the active input handling setting?
you mean this?
no, i mean the setting that is literally called Active Input Handling in the Player settings
I dont get it
your !IDE is not configured
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
i just updated it
what do you not get? do you know how to get into the Player settings for your project?
okay so complete all of the steps to configure it
you'll need to provide proof - because neither of the screenshots you've shown, have it configured
I dont get what are player settings nor how to get into them?
literally first result searching "unity player settings"
https://docs.unity3d.com/Manual/class-PlayerSettings.html
Why in the guide nothing was told about this
how should i know? but the option to enable the input system was given to you immediately after you installed the package
Huh, dont remember. Probably missed it.
you can't miss it. it's a pop up window that prevents you from doing anything else until you've clicked yes or no on it
I was at same time looking into the guide when it was installing
what guide? the video you screenshot before?
Yeah the Unity Input
link the video
https://www.youtube.com/watch?v=UyUogO2DvwY&t=509s
Its one of shorter ones, not like long ones dont waste 80% of time setting inputs for everything
In this video I walk through step by step on how to move a simple 2D sprite using WASD, Arrow Keys and the Left Analogue of a controller.
Starting Project GitHub: https://github.com/LMutlow/YT_Input_Tutorial
I'm still new to making these tutorials so please leave any feedback or ideas for future videos in the comments section below!
1:09
Dont remember this happening
I mean, "setting inputs for everything" seems to be pretty important. Considering you apparently haven't
Just start over
Despite the inclusion of the RectTransform difference in the code, the origin of the grid is always the bottom right corner of the screen. This persists if the anchor is set to the top right, as well.
get its anchored position not its position
also you don't need to use GetComponent<RectTransform> you already have a reference to the transform, just cast it to RectTransform instead
like this?
Is this a relatively recent change? The guide I'm following is two years old and didn't mention it
no, it's how you've always had to get the anchored position of the object
this script works. but i want to replace Input.GetKeyDown("a") with Input.GetAxis("Horizontal")
problem is, Input.GetAxis counts as a float not a boolean so it doesn't work with the If statement
is there any way of making this happen?
compare it against 0
does it automatically gain a higher value than 0 when activated or do i have to assign it that value
Input.GetAxis will return a value from -1 to 1 depending on what is held for that axis. when nothing is held it will be 0
although GetAxis has some input smoothing so you may want to use GetAxisRaw instead
does anything else need to be changed for GetAxisRaw or can I treat it the same as GetAxis
why don't you take a look at the docs and see what the difference is
there are beginner c# courses pinned in this channel, perhaps you should start there
alr well i figured it out
the answer to this was "yes (you can treat it the same)"
and the answer to this was "yes"
i feel like checking the documentation and taking courses would have just wasted time lmao
you are right. and anyone with basic knowledge of the language would know that. if you don't want to learn the basics then don't expect much help here
yeah but I mean like, I was just double-checking yknow
you didnt need to act like i was completely wrong and clueless if i hit the nail on the head
kinda misleading
There were almost three minutes between your question and your answer. In that time surely you could have hit Ctrl+T and typed this into google and seen the giant info card
bro this discord isnt my top priority
"there were three minutes between your question and answer" đ
i spent 30 seconds changing the code to see if it worked, it did, and then i went back to the unity course i'm following
My point is that you literally didn't even need to ask the question. It took you longer to type the question than it would to just plug keywords into google
i only asked the questions here because i thought i'd get a straight yes/no answer and not "try checking the docs"
point is, isn't this chat supposed to help beginners instead of just directing them elsewhere
ah
yeah you know what thats on me then, fair enough
didn't see that lmao
my baddd
Seriously, typing the question into google is faster than wasting everyone's time expecting someone to answer it for you. You could have spent less overall time for fewer people by just googling basic syntax questions
Hi. If I send my codes now, can you check my error?
you can just share your issue and relevant code and errors in here and anyone who knows how to help you can do so
ok thank you very much. Before I updated my code, everything was working fine, but the changes I made to the code caused the problem. But I don't know what happened. I would be very happy if someone who knows could help me. I'm sending the codes now.
i googled how to use the Material.SetColor() and idk what context i have to use it in is it the public void or is it within a public void i just dont understand how to use it i need to use it for my assignment to make it change the color of an object when i apply it to my ray cast it needs to toggle for said color back to default or reset back to default
It's a function you call when you want to set a Color property on a material
public void doesn't mean anything, that's an accesss modifier and a return value so I have no idea what you mean by that
hey guys so how do i check if an object is facing another specific object
thats what i ment by that but thanks for explain
I have no idea what language this is in or what the issue is but general takeaways just glancing at it:
- When you find yourself numbering variables, you probably want to use a list
- When you're doing the exact same code with the exception of what variables it's affecting, you should use a loop
Why are you trying to make a new function and why does your function have a . in its name
yeah i'm not gonna be able to parse that. i don't read whatever language it is you code in đ€·ââïž
Hello, how can I make my character speed vary from joytick tilt ? I have a vector3 made up from vertical and horizontal values, I tried to multiply it by the sum the horizontal and vertical values, but it doesn't work because it's slowed down diagonally
My problem is that the script inside the object does not run unless I click on the object where the script is located. The object I call is the player.
what do you mean by "vary from joystick tilt"? and how are you getting your input
please may someone help.
Get the direction from one object to the other, then use the Dot Product of that direction and the object's transform.forward. Dot Product is closer to 1 the closer the vectors are to the same direction. You can check if the value is greater than some amount, and adjust that amount for how much "sameness" you want to check for
Try different values to see which one is close enough to what you're expecting
Like the more you are tilting it (approaching it to the value = 1), the fastest the player is. I get my input with Input's manager joystick X and Y axis
show your actual code for how you get input
float vertical = Input.GetAxis("Vertical");```
thats it
no it isn't. show the full !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.
Sorry i am creating a enemy who walks towards the player rn but everytime the enemy starts walking it then suddenly stops for 10 seconds then continues ```c#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CowboyAnimationScript : MonoBehaviour
{
// Start is called before the first frame update
public Animator cowboyAnim;
public Transform lookObject;
public float maxTurnSpeed = 50f;
private void Awake() {
cowboyAnim = GetComponent<Animator>();
}
void Start()
{
}
private void Update() {
Vector3 direction = lookObject.position - transform.position;
transform.rotation = Quaternion.RotateTowards(transform.rotation, Quaternion.LookRotation(direction), maxTurnSpeed * Time.deltaTime);
cowboyAnim.SetBool("walk", true);
}
}
That will get you a value between -1 and 1 depending on the degree to which you are moving the joystick. As it approaches is maximum value in that direction, it approaches 1
Nothing in this code moves the player. This just animates
programming language c# normal language Turkish
and again, i don't read turkish. i cannot read your code. therefore i cannot help you
ok
idk thats heonstly how it seem like i had to use it
Which is a sure-fire sign you don't know basic C# syntax. Check the guides in the pins. Learn what a method is and how to call them
i think he/she just does not understand the syntax for C#
Exactly, which is why I said to look at the pins
Specifically the intro to C# course linked
well it was more the fact the website didnt explain what it was it said what it was not how to use or a good example i understand syntax i was getting pissed i could not figure it out that i tried it to see if it would work
it is not the player it is an enemy and it does move it because of what the animation is jĂșst please explain why it is pausing midway
Nothing in this code moves the enemy. This just animates
how
Read the bot
thats what i was using i was confused cause ive never use any set color or color related code before
You call the function
with the parameters you want to use
animations can change position
Then if that's the case I'd say the reason your position isn't changing is because your animation isn't changing its position
it is however it is taking pauses inbetween
so this code is going to be apply to my ray cast interact script i attach it to ray cast and set the toggle and im able to click e for it to change color is the end goal so that means i can change any object color that has my interactable script to it so when unity documentation site say cubeRenderer.material.SetColor dose cube renderer mean just strictly cubes or what cause i assumed i could use mesh renderer cause i have that on all my game objects and apparently i cant use mesh renderer to replace it so what do i have to do?
where have you declared the variable called meshRenderer
What is meshRenderer
Probably because your animation is telling to do that
even though before the code it just kept the animation going
why cant i drag my image into the "source image" of the image component??
cause its not a sprite ?
also not a code question
its a png image what else does it have to be
A sprite
in the import settings
which is not code
ok thanks
idk i didnt have a cube renderer like how the site said and it flashed error at me so i tried to see if it had to be mesh renderer
You have to use a variable that exists
Do you have a variable named meshRenderer in your code
What are you trying to get the material of
yes but i 100% sure i called it wrong and the end goal is so when i apply it to my interactable ray cast i can look at a said object (any object in my game) and tap my interact button it will switch the color to any color and i was told i have to use material.SetColor to do so
What is this
Seriously, stop guessing
learn C#
there are beginner c# courses pinned in this channel. you should start there instead of attempting to code by approximation
im in class trying to learn im taking mastery coding provided by my tech school and its ass at teaching
just a quick question do you have to use visual studio for unity?
you should try doing beginner coding before mastery đ
it is
am i missing a package if its grayed out?
your options for supported IDEs are Rider, Visual Studio, and VS Code. that also happens to be ordered from best to worst
Mastery Coding provides award-winning esports and computer science curriculum for schools. Put your students on the pathway to college scholarships, industry certifications and multifaceted opportunities in emerging technologies.
Then you should start learning on your own
why is rider better?
what's grayed out?
cant access it
what
or is it more personal preference?
what is "it"
better features, better analyzers. jetbrains products are just great in general
ahh yea its read only
i have but i dont get time to cause i have to complet mastery coding then take my certification test for C# that im going to fail and then make a game
make a copy is usually fix too
idk bro i just right cliekd my sprite folder and clicked import new asset
tanks
Well if the end goal is a certification for knowing C# then you demonstrably do not. Helping pass that would be academically dishonest
You are able to learn things outside of a school environment you know. If the class isn't teaching you, there are myriad resources available to learn on your own
like the ones in the pins I keep referring to