#π»βcode-beginner
1 messages Β· Page 435 of 1
cant it point in two opposite directions though
For my player when using keys it moves {60, 0, 0} which is forward but for my button it moves {0, 0, 60}
not in your c... oh... eh... lets say, you detect that and use the last known value or something
technically it's just not defined in that case
AddForce is local by default
not sure what's going on because too much to read... but thought I'd mention it π
try using rb.AddRelativeForce
Alright for the button?
wait, it's not local? I guess I'm misremembering something π€ if it's world it should be the same
for both
Akr
as far as im aware.. AddForce(transform.forward) and AddRelativeForce(Vector3.forward) would do the exact same thing
yep, you are correct... I was thinking of transform.Translate, which has a parameter for local or world, my bad
I actually found the issue with my code and I think it works fine now
you can only move the remaining distance from your current angle to the max angle right
I was getting the angle from the base vector and the DESIRED vector
not current
Now its reversed, the key moves it sideways and the button moves it forward so i should add relative to the button and remove the one from the key?
that'd work π
Hello, I want to get the position of an object. Obviously transform.position comes to mind, but this object is a prefab and therefore I can't get its position that way. Is there any way to get the position of a prefab?
That does get the position of the prefab. It'd be the value you set in the inspector for the root object of the prefab
a prefab shouldn't have a position π€ until you instantiate it into the scene. at which point u'd get a reference to the spawned prefab..
and that would have a position
not sure exactly where to ask this but anyone got any idea why my script is acting like this... i cant interact with it at all.
Tysmm
ive tried restarting the editor
looks like a broken custom inspector
it is, thank you. not sure why though π
nevermind forgot GUILayout.EndHorizontal(); π
That's what I assumed when making this code, but it still is returning 0, 0, 0
First, debug.log return
Second, prefab actual transform
Third, Debug.log call returning first value
The third one is printing the position of whatever object this script is on
If that's the prefab, then this code wouldn't be running, because prefabs don't run any code
The prefab has been instantiated
So you're printing out the position of a specific instance
and the values on the prefab no longer matter
hey guys!
how can i create a material instance, that is shared between several renderer components?
i tried this but it doesn't seem to be working.
I'm trying to get the position value of a specific instance from code, but it keeps giving me 0, 0, 0. The actual position of the instance is the second image
What you see in the inspector is the local position, the object's position relative to its parent
It is entirely possible the object with that transform is at 0,0,0
debug localPosition and you'll probably get ur values u see in the inspector
#βοΈβeditor-extensions is probably the place to ask this
oh woops
You have officially left the realm of beginner and into specializations
hehe π
Still get 0, 0, 0. Is it possible that calling methods from a prefab the line after it was instantiated can cause issues?
not sure, can't say ive tested that.. i can tho
You're instantiating a clone of the prefab, then calling a function on the prefab
you are not applying any parent there so transform.position is the same as transform.localposition
it looks like ur trying to grab stuff from the prefab
and not the instance of hte prefab u spawn
That's definately the issue
spawnedPotAura.GetComponent<>```
need to access it thru a reference u assign when u instantiate it
I'll try this, should work. Thanks for the help
Seems to have fixed it. Thanks a ton!
I have a class Player with hp. I have an Item class which has capabilities like increasing hp. How do I best send the information to increase hp to the right instance of player when an item is gained?
i'm following brackey's tutorial on top down movement in unity and it says that i have to move the rigid body component there, but it won't let me. does anyone know what could be causing this issue?
a Rigidbody and a Rigidbody2D are different things
Rigidbody is not Rigidbody2D
Your variable wants a Rigidbody. You're trying to drag in a Rigidbody2D
omg thank you so much haha
assuming u actually interact w/ the Item.. you should have a reference to the player..
referenceToPlayer.GetComponent<Player>().AddHP(itemPickupAmount);
thanks spawn. trying it now
I use a GameManager/PlayerManager singleton so it has a reference to my Player / anything important I need to access frequently..
then its just PlayerManager.instance.AddHealthToPlayer();
or PlayerManager.instance.AddToInventory(item);
it worked spawn. Just did getcomponent. I am curious about the way you implemented it though. I don't really understand the use case of adding .instance on setup
i have seen it in code tutorials
https://www.youtube.com/watch?v=yhlyoQ2F-NM&ab_channel=GameDevBeginner heres a good breakdown real quick
Want to know how to CODE in Unity? Go here: https://gamedevbeginner.com/how-to-code-in-unity/
Learn the pros & cons of using singletons in Unity, and decide for yourself if they can help you to develop your game more easily.
00:00 Intro
00:47 What is a Singleton?
02:39 Why use a Singleton?
03:00 Drawbacks of using Singletons
05:45 Is it ok to ...
This should instantiate a bunch of trees right?
Instead it returns a null reference
on what line
21
I did all this before, but my hdd got corrupted so im trying to remember how i did it all
i feel ya π’
Conveniently easily discernable from the snippet you've posted
oh i see sorry
since u code doesnt have line-numbers we need a bit more info π
Either parent is null or gameGrid is null
Kinda need help with a problem I have.
I have been trying to make class that basically waits X seconds to do something, its basically a timer
public class EsperaSegundos : MonoBehaviour
{
float _seg;
public EsperaSegundos(float seg)
{
_seg = seg;
}
public bool Contador()
{
_seg -= Time.deltaTime;
if(_seg <= 0)
{
return true;
}
return false;
}
}
So whenever the seconds is <= 0 it returns true so the timer has finished.
The idea is that the method Contador() is going to be called inside an update of another class.
However, the problem comes when instantiating this object with a constructor in another script:
EsperaSegundos esperarSeg = new EsperaSegundos(_secondsPerAttack);
This is what I have in mind but it wont work
void Update()
{
EsperaSegundos esperarSeg = new EsperaSegundos(_secondsPerAttack);
if (esperarSeg.Contador())
{
Instantiate(_bullet, _bulletSpawn.position, _bulletSpawn.rotation);
}
}
What am I missing. I dont know much about C# but in Java I think this is how it would work.
Any ideas?
not a good plan, you should be looking at Coroutines
You cannot create a monobehaviour with new
And any constructor in a MonoBehaviour will be ignored
You should look into coroutines:
https://docs.unity3d.com/Manual/Coroutines.html
I actually did it with a coroutine but trying to figure out if this way will work
well, to be blunt, no it wont
you're making a brand new timer every frame
Is it possible to do it this way?
no
yes it's possible, not with your exact current code
True, will place it in start
you cannot create a MonoBehaviour with new
and if I remove it?
something similar to this is possible
And possible doesn't mean good. This would still be incredibly wasteful even once you sort out the creation of a new class to hold the timer. It's just gonna exist forever until GC'd
but not this exact thing
you should also never intentionally pause the Update loop
it actually doesnt pauses it
sine it will just return false
but I think it is just better to use coroutine instead :P
π―
is there a reason I shouldn't use them?
a coroutine?
or its just objectively better?
yea
it's the tool Unity gives us to do the job, so take your pick
Alright
Here's an example of your concept that would work https://hatebin.com/deflstzmhz
but there are definitely cleaner ways to do this.
https://www.reddit.com/r/Unity3D/comments/128z4pr/discussion_is_it_a_good_practice_to_just_avoid/
consensus says only if u over-use them
i'll write a timer in update from time to time.. but for most cases i use coroutines daily
Besides this is barely any more convenient than just making a float variable and decrementing it yourself
so it's hard to really see a huge benefit here
I see, its a lot cleaner than mine x). About the struct you make, is this something you make inside the same script, whats the difference between this and making a class
It can be in the same file if you want but more likely I'd put it in a separate file entirely since the idea would be to reuse it in many places
small data structures are better for structs
Structs are different from classes in that they are value types instead of reference types
it's kind of a subtle difference if you're a beginner
but it's quite important
For the life of me i cant remember how i made a 2d array of trees o.O
Should work right? But it returns null
Oh right it's populating the trees but on 1 spot lol
What line is the error on in the newly updated code?
There isn't any, just not doing what it did previously which was a grid
Before it looked like this
let me find my screenshot
wdym by a grid? The hierarchy has little to do with your array
That does seem to be spawning a tree at this object's location
one for each square in the grid
the array is definitely conceptually a grid
Thats what i worked out before my corruptions
Nothing in here is putting the trees at any different locations
Your code is spawning them all at the same position
not sure why you'd expect any different
"null" is printing because you're printing the array elements before you assign them of course
literally on the line before you assign
Yeah i saw that part
So the grid is working in terms of it's going through from 0 -> 15 on i and j
but im trying to recall at each iteration of i / j is a new tile
within my game world
Your code spawning all the objects at transform.position. The code is doing exactly what you wrote.
Yeah i understand transform.position is just 0,0,0
I assume you're using a tilemap here
The background is a tilemap, but the gamegrid isnt
it's gameobjects which i lined the array up
what's the gamegrid
Like this ^
you need a Grid to convert grid coordinates to world space coordinates
Your array is a data structure
it has no inherent connection to the game world
Then i used "continue" to skip parts of the map i didnt want things to spawn
you can and should use https://docs.unity3d.com/ScriptReference/GridLayout.CellToWorld.html to get the world space position for each grid coordinate
I'll take a look, thanks
(Tilemap has this)
You can also have a separate Grid component to handle this if you wish
with whatever grid size/shape you want
Did it my own special way, but you pointed me in the right direction π
Need to sort out the layering etc
btw for performance and memory reasons it's probably better to explore using a tilemap for these trees at some point.
Presumably it would need to be a tilemap of trees and that tilemap would need to have a collider on it
yes a tilemap collider
of resources*
Sounds doable
You might cry if i told you how i achieved the above screenshot, 2 up from here
I assume it's just a bunch of funky looking arithmetic in the loop
i had it check each position for a tree:
xxx
xox
xxx
with the tree being the o and nothing surrounding it
eatingcoroutine = StartCoroutine(Eat(furthest));
StopCoroutine(eatingcoroutine);
guys this is supposed to end the coroutine no matter what right?
yes it will end the coroutine, assuming the StopCoroutine line actually runs
note that it only stops the coroutine when it's waiting at a yield instruction.
(because coroutines only pause at yield instructions)
ohh ok it does run i checked using debug.logs but it wasnt ending tho
what makes you think it's not ending
it has a visual aspect to it
anyway I assume that's not the real code since it would be pretty strange to stop a coroutine directly after starting it
ofc no π
Time to whack it now in a coroutine and watch it populate to make sure the logic is how i remember
showing the real code and surrounding context may help us identify the problem
the code is a bit long for a message how can i send it?
Need some help on rotating 2D enemies so they can constantly look at the player without oscilating in a weird way. I've tried using quaternions and also using the rigidBody method AddTorque(), can't figure out what's the best way
!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.
do you need it to be physically realistic? Or just a lock-on effect
the simplest way is just:
void LateUpdate() {
transform.right = target.position - transform.position;
}```
if(eats.Count > 0)
{
if (furthest == null)
{
furthest = eats[0];
}
foreach(GameObject plant in eats)
{
if(plant.transform.position.x > furthest.transform.position.x)
{
if (eatingcoroutine != null)
{
StopCoroutine(eatingcoroutine);
}
furthest = plant;
eaten = true;
}
}
touchingplant = true;
if (canEat && eaten)
{
eaten = false;
Standing();
anim.SetBool("isWalking", false);
anim.SetBool("isEating", true);
eatingcoroutine = StartCoroutine(Eat(furthest));
}
}
else
{
furthest = null;
eaten = true;
touchingplant = false;
anim.SetBool("isEating", false);
anim.SetBool("isWalking", true);
}
public IEnumerator Eat(GameObject furthest)
{
if (furthest != null && furthest.gameObject.activeInHierarchy && currentHealth > 0 && canEat)
{
furthest.GetComponent<UniversalPlant>().Damage(damage);
yield return new WaitForSeconds(damageDuration);
StartCoroutine(Eat(furthest));
}
}
It runs after every object's Update
Full !code, use a paste site
π 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.
This wouldn't work in Update() method? Has to be LateUpdate()?
hi
Your coroutine is starting other coroutines:
furthest.GetComponent<UniversalPlant>().Damage(damage);
yield return new WaitForSeconds(damageDuration);
StartCoroutine(Eat(furthest));```
Those other coroutines won't be stopped by stopping your original coroutine
I want to ask how do I change variables in one script using another script
You would want it to be LateUpdate so it's guaranteed to run after the object you're trying to point at has moved
It would more reliably point directly towards the object in LateUpdate since it guarantees that all Updates have run, which might reposition things
hmm ok what can i do
ill see it thank you
stop doing that
if you want to repeat code
just use a loop
Oh I see
This should populate the array, down then right no?
you need to start with rows - 1
and go to j >= 0
for (int j = rows - 1; j >= 0; j--)
Yeah i understood, thanks so much π
Cheers mate
Also I am interested on how you can do it making it physically realistic since I have also been trying to do it but ran into a few questions.
ΒΏIf my enemy is moving using the rigidBody component, should it rotate using transform.rotation, or using the AddTorque() method? and also
ΒΏWould this be inside Update() or FixedUpdate()?
After watching lots of videos I made them rotate like this (physically realistic), its inside the FixedUpdate but not sure if it belongs there:
(Inside FixedUpdate)
Quaternion rotation = Quaternion.LookRotation(Vector3.forward, _dirJugador);
transform.rotation = Quaternion.RotateTowards(transform.rotation, rotation, _rotationSpeed*Time.deltaTime);
The problem with this is that I had some oscilating problems.
So what would be a correct way to make it rotate in a realistic way
if you want physical realism you should basically only be using AddForce and AddTorque. Never touch the Transform directly
to do it realistically you would basically need to use a PID controller
in real life things can't rotate instantly on a dime. They have inertia
Can you rotate using AddForce?
so there needs to be a period of acceleration, then deceleration
no
it always adds forces at the center of mass meaning there will be 0 net torque
hence no rotation
Do you mean AddForce and AddTorque?
in class player, I have a field called totalDamage. When I instantiate a bullet, I access class Bullet with GetComponent and pass along the totalDamage for .Setup. The Bullet never receives the value of totalDamage. Is this because its a class field? Can it be cast as just an int?
It never gets it and I get a null reference error
I access class Bullet with GetComponent
No you are trying to get a reference to an instance of that class with GetComponent.
It never gets it and I get a null reference error
This means the reference you got was no good. It wasn't actually pointing to an actual instance of the Bullet class
Just saying you used GetComponent is really vague
Can you show your code and show what line you got the NullReferenceException on?
There's a much better way to do this:
public Bullet bulletPrefab; // assign this in the inspector to the prefab
public int damage;
void SpawnABullet() {
Bullet bulletInstance = Instantiate(bulletPrefab);
bulletInstance.damage = damage;
}```
no need to use GetComponent at all
and this also makes sure you don't make any mistakes in the editor when you assign the prefab
About this. Using it in LateUpdate() will give me chunky movements, is it for mixing rigidbody movement and transform movement? But if I use it in FixedUpdate it works perfectly. Is this the viable solution?
The solution is to continue to use LateUpdate, but enable interpolation on the Rigidbody
It is activated
how is the Rigidbody moving
And _dirJugador and _speed are calculated as?
_dirJugador = (_jugador.transform.position - transform.position).normalized;
float _speed = 3.0f; (constant)
Btw is this the best way for a lock-in moving direction towards player?
hmm you shouldn't get chunky movement with this
can you show a video perhaps?
Sure
here is the messy way I am doing it right now. Still not sure why totalDamage never gets setup on Bullet. I am sure it is getting the right component.
the debug.log for totaldamage at the top works fine
If that's giving you a null reference exception then the VfxSlssh object does have a Bullet component on it
Which is a mistake my code wouldn't allow you to make
Part of why I recommend that approach
the prefab does have the Bullet component. appreciate the feedback, I do have to refactor a lot of this
If you are getting that exception, it does not
Feel free to show some screenshots to prove me wrong
Also seeing your exact error message might be helpful
Transform does not have anything named totalDamage
right, just testing something there
Why does changing 30->36 throw an error?
Ah the nested for loop is in the wrong order presumably π€ I needed more rows than columns, so the rows couldn't be nested.
does anyone know why my drag and drop system for an inventory doesnt work? it works fine in a completely new project but doesnt in the current one
item slot - https://hst.sh/ariruvahas.csharp
dragDrop - https://hst.sh/vakahelodo.cpp
Hey guys, I'm planning on making a script that will realistically control a rocket. I'm wondering how I would go about it. I want it to go by a realistic (yet simplified) version on how orbits work. I'm not sure what channel to put this in, I'm putting it here because I'm a beginner. (I want it be like how ksp does it)
https://assetstore.unity.com/packages/tools/physics/simple-kepler-orbits-97048 heres an asset taht was helpful when i was doing a rocket prototype
Does anyone know how to solve the sensitivity issue for exporting unity builds to WebGL?
your error doesn't match the code
make sure you save your code changes and show the actual code that caused the error
And please share code not with screenshots π
I fixed the issue
I think it was because the nested loop was running more than the outter loop
Making the rows the outter loop, with the columns the inner resolved the issue
that's not in and of itself a problem
{
[SerializeField] GameObject player;
Vector3 playerPrevPos;
// Saves player position on start then changes if different -5 from currentPos
Vector3 currentPos;
// Saves current position of the platform
public float distance = 5;
// Distance between the player and death platform
void Start(){
currentPos = gameObject.transform.position;
}
void Update(){
playerPrevPos = player.transform.position;
if ((playerPrevPos.y - distance) > currentPos.y){
transform.position = new Vector3(currentPos.x, playerPrevPos.y - distance, currentPos.z);
currentPos = gameObject.transform.position;
}
}```
Any glaringly obvious mistakes with my script that'll the current position of the platform is more then distance it'll change the platforms position into the players position - distance?
Your problem here was actually you mixed up rows and columns @plush palm
{
for (int j = columns - 1; j >= 0; j--)
{
//Debug.Log("J: " + j + " Rows " + rows);
//Debug.Log("I: " + i + " J: " + j);
//gameGrid[i,j] = Instantiate(resources, gameGrid[i,j].transform.position, Quaternion.identity);
SpawnTile(i, j, gameGrid[i, j]);
Debug.Log("i: " + i + " j: " + j + " Value: " + gameGrid[i,j]);
}
}```
it's overcomplicated for sure
but works?
I'm unable to check without putting it into a different unity file because I don't want to push a bugged script into my git main
I think it probably only works in one direction
that's the goal
if it works at all
it's gonna be like the death thing in doodle jump so I don't need it to follow x or z
hard to say with all the subtraction if everything is right. It could very well work. Best to test it

hello, is it possible to detect if a variable changed from a state to another in one frame?
Have the class that has the variable notify you that its changed. Like through an event
i wanna know when it changes from a specific value to another specific value
sure, compare the old value to the new one and use an if statement
Use an event to track when the value of a variable changed to notify anything that wants to listen (subscribe) to the event . . .
ok i'll see what i can do
guys can i make 3d game but with this view?
that doesn't seem like a code question. but why wouldn't you be able to
idk it is look werid
So, I have a navmesh agent on an "enemy" and I have it go to the player, and that works fine, but I have a retreat coroutine that has that enemy back away from the player until a certain range, although the issue is, the agent destination is getting set properly and it can be reached, but the enemy doesn't move and just stays in place, is there something im missing?
Probably
Is there any ideas that I should be checking for? All im doing is setting the destination to behind the enemy
show code
Is it far enough outside it's stopping range? Distance*
But yes. Share code too
It might be, I can try checking that
IEnumerator Retreat() {
isRetreating = true;
anim.SetTrigger("Retreat");
GameObject closestPlayer = FindClosestPlayer();
if (closestPlayer == null) {
isRetreating = false;
yield break;
}
Vector3 retreatDirection = (transform.position - closestPlayer.transform.position).normalized;
lastPos = transform.position;
while (Vector3.Distance(closestPlayer.transform.position, transform.position) < retreatRange) {
Vector3 randomDirection = transform.position + retreatDirection * retreatSpeed;
if (UnityEngine.AI.NavMesh.SamplePosition(randomDirection, out UnityEngine.AI.NavMeshHit hit, 10f, UnityEngine.AI.NavMesh.AllAreas)) {
Vector3 retreatPosition = hit.position;
agent.isStopped = true;
agent.ResetPath();
agent.SetDestination(retreatPosition);
agent.isStopped = false;
}
yield return null;
}
isRetreating = false;
}
All of the agent reset/isstopped was me testing different things
you stop it every frame until the distance is more than retreatRange. what is the point in stopping it anyway? just set its new destination
I was stopping it to maybe see if that was the issue, since I wasn't too sure what the issue was
okay well stop that. then read through your code very carefully
tell yourself what each step of that does. then consider why you've done that, you might figure out the issue on your own
Yea, I think spawn camp kinda helped me realize the issue, I don't think its distance was getting set outside of the stopping distance so it didn't move
U can change that on the fly too
Depending on if it's rushing retreating or w.e
To fine tune ur enemy
I wanted the enemy just walk backwards as a retreat, not rushing or anything like that
Getting on state machine territory π«£
Just saying it's possible to change the stopping distance if need be
So ur not stuck w a single
Value
Yea, I might look into that as well, thank you for the help
is there a way to get scriptable objects in a list quickly, or do i have to put them in a list manually?
get which ScriptableObjects in a list quickly?
your question is pretty vague
You could have an editor script/OnValidate that scans a particular directory with AssetDatabase to populate them all from a folder
or just select them all and drag them into your list
ok thx
why does the first block of code (represents image with fewer cubes) produce a different set of points than the second block of code (represents image with more cubes)? All variables used have the same value, including StartPoint and checkNavmeshSpot.
https://gdl.space/vimocunaqe.cs
https://gdl.space/tegicomipa.cs
You'll need to debug it
kinda weird that unity would complain about use of an unasigned int when by all rights it should default to 0
How can I disable player input (movement, jumping, etc) when editing InputField?
use OnValidate() to validate the data before it's ready
Can't think of any situation where you'd use an inputfield for player movement, but if you want to not actually do anything with the input until it's finished you can just use onEndEdit instead of onChange
I mean, when I'm using input field I do not want to player be able to jump, move, etc
the text mesh pro input field has a ton of events you can tie into
https://docs.unity3d.com/Packages/com.unity.textmeshpro@1.3/api/TMPro.TMP_InputField.html
I think C# won't initialize local variables with defaults on the whole, if that's what you were talking about... As a field, it should still default to 0
Oh the easiest way to do this depends on how you have your UI setup
nah just a declared local int, I'd think maybe a warning would be ok, but an error?
It's basic TMP InputField
No, as in the hierarchy
Ah
and the overall ui flow
if a player is either in game or in a menu, you can just check whether any menus are open before processing input and exit if yes
if you have UIs mixed into the world, you'd just set up a bool and add events for whenever the player starts and finishes editing text to enable or disable input
iirc eventsystem also has information regarding selected UI elements
yeah @muted narwhal all you're going to do is query your eventsystem and see if the current selected object is null or an inputfield
private bool IsAnyInputFieldFocused()
{
return _inputFields.Any(inputField => inputField.isFocused);
}
if(!IsAnyInputFieldFocused)
movement code here
Would something like this work?
static void Main(string [] args)
{
int x;
Console.WriteLine(x);
}
sure enough it does compile to an error, I must be rusty, still I'd argue it should just be a warning
Probably, less efficient though since you're checking every element instead of just one and depends on you including all your inputfields in that collection
I feel that... it is a bit of interesting decision on Microsoft's part to only initialize to defaults in some places
private bool IsInputFieldFocused(){
var selectedObject = EventSystem.current.currentSelectedGameObject;
if ( selectedObject == null ){
return false;
}
return selectedObject.GetComponent<TMP_InputField>() != null;
}
Came up with something like this.
Ironically a c;ass variable will default to null and it will let you hang tyourself all day long with it lol
to be fair, why would you ever wanna do this? It'd clearly be a bug. I think that plays into why its an error
It would save a tiny bit of processing time. In C, it would be similar to allocating new memory and zeroing everything out versus just simply allocating new memory without zeroing.
A local variable introduced by a local_variable_declaration or declaration_expression is not automatically initialized and thus has no default value. Such a local variable is considered initially unassigned.
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#929-local-variables
I guess it sorta depends on if an int is defaulted to 0 in the specification or if that is implementaion specific. If it's that way in the spec then they are both saying it will be defaulted and then expecting you to officially initialize it tool
It should definitely throw an error and not a warning unless Microsoft ops to default local variables instead of allowing devs to explicitly do so themselves.
Ah interesting - and good analogy!
One thing to watch with this is that it doesn't remove the current selected object on submit
If you look at the lower right corner, selected only clears when I click outside of the inputfield, and not when I press enter, whcih is something you'll want to be careful of
How can I fix that?
It appears to be spec based on constructors
Edit: Or rather the bit Dalph linked explicitly mentions locals having no defaults. So yeah, explicitly spec'd without contradiction - just unintuitive :P
if (inputField is { isFocused: true })
is there a way to hard break running code? I ended up with a tight infinite while loop and pause or play didn't cause a break. Or is end task the only way?
I am trying to teach myself c# so I can use it with unity but I cant even create a simple "hello world" program because I get this error
Also when I try to run it im told the file cant be found but whe I check the directory its still there?
!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
If you attach a debugger, you can pause execution and change a value in memory to either exit the loop or throw an error. I usually set something to null to get an NRE
You may just need to install the x64 version of the SDK (and then restart your computer)
figures, I was able to attach debuggre, but no source code available...which is probably due to my onw needing to configure the IDE properly π
I followed the "!ide" command from that other dude and I had already installed the SDK so I restarted my computer but I am still getting the same erros
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 don't use VSCode for Unity myself, so I may only have limited insights here. But the error seems to indicate that it found a 32 bit SDK, but that the C# Dev Kit extension requires a 64 bit version. If you open Windows' "Apps & Features" and search for "SDK" what does it list?
I know not all of these are relevant but that is absolutely everything that shows up
Ah shucks... hmmm
yeah exactly what im confused about
I tried uninstallying vs code multiple times
restarting
could i redownload some of the sdk's?
i dont want to fuck up my computer obviously and im not exactly sure what is and isnt safe to download
anything interesting when you clicked Open Log in the dialog?
is this on a PC or mac?
windows
The very limited discussion in this issue seems to indicate that it might be defaulting to whatever's found first in your environment path...
When I open a terminal and execute
dotnet --info
it provides quite the info dump, but among it I can see that the dotnet resolved on path is at C:\Program Files\dotnet\sdk\8.0.303\ and another for x86 in C:\ProgramFiles (x86).
I don't see a means to explicitly set it in the C# Dev Tools extension... If this is the case, you may need to change your environment path, or launch VSCode with batch file or some such
My own environment path only has C:\Program Files\dotnet\ as far as dotnet entries go
how would i go about changing my environmental path
and are you saying i would just need to move my project files there?
also how can i identify my current environmen path
Nono, just changing a variable on your windows system :P
Hit the start button, type "env", select "Edit the System Environment Variables." Click the "Environment Variables..." button on the bottom right. Select "Path" in the "System variables" section and hit "Edit"
You could probably just add C:\Program Files\dotnet\ to the top (or move it up if it already exists and is buried in the list)
If something else was depending on dotnet resolving to 32-bit version, this may interfere with that functioning properly, however. It's a shame C# Dev Tools doesn't let you explicitly set the path to your choice of SDK π€
this is what comes up, does tha tmean that if i want to now do a project it should be within these file paths. im slightly confused as to what im doing with these. follow up, if i simply add a new file path here can I then put my project files there as well?
is that what im looking to do?
When you or some other program executes a command and Window's isn't sure where it resides, it'll search all of the paths in the environment path list from the top down looking for that command.
In this case, if something's looking for dotnet, it seems something at some point added an entry that's causing one of your 32 bit SDKs to be found before the 64 bit versions. So by putting the path to 64 bit version earlier in the list, things looking for dotnet should find it first instead
That would be the user environment path - which would work for this, it'll just apply to your user instead of the system. I think that should work π
Ah hmm
so will i need to restart and then try to run my code again and that should fix it entirely?
I have that same %USERPROFILE%\.dotnet\tools entry...
I think just closing all instance of VSCode and starting it again should be sufficient... but now finding this entry in my own path I'm not certain. I'm not so familiar with dotnet and it's configuration π
Im still getting the same exact issue im gonna go to bed cause its late and ill probably have better luck with fresh eyes tomorrow. thank you so much for your time i appreciate it
Godspeed π«‘
Hopefully tomorrow someone will be around with a better handle on things
if it helps, there seems to be tons of people with similar issues on google searchs related to same error. Of course every solution seems to vary for each of them
That sounds more promising than my single-comment-inspired goose chase, at least π
Anyone you what the deal is with this error? the object exist, and that refernce to it's sprite renderer works in other parts of th escript
extrastars is null
Why does it matter though? I'm adding to it, not reading it
You're referencing a null object
you csnnot add to something that is null
ohhh, okay. So how do I add the Spriterenderer onto the list, instead of what I assume is a maths method
Just make the list not null
You have to initialize the list before adding something to it
you need to initialize your list
How? I mean I know if it was an array I would say like, = new Spriterenderer[number]
but lists dont work like that right?
vey close to that, yes
new List<MyType>();
damn, you guys just racing to see who can respond first?
LOL
oh alright, thankyou!
we're in sync xD
well oiled machinery
Let's go kaihyo
wait lemme test something...
how do I run a coroutine?
perfect, thanks
If the manual is not enough: https://unity.huh.how/coroutines
I've just done the Junior Path On U Learn and I don't really know if I should jump into some small project and learning, searching from that or find some more course on Youtube... What did you guys choose ? I need some advices, kinda lost now 
Hey guys, do I need to use gettes and setters for all my variables inside player etc? or just the most important ones? If you are creating a game alone should I even care about this?
Hello I'm new here and I have an issue with my unity is there anywhere I can possibly get some assisstance?
You're in an entire server where you can get help. Just post your problem in the correct channel
how can i change the postive and negative buttons by code?
Hello, currently I work on a Tycoon and I struggle a bit with inability to choose way to store sprites of each building from blueprints. With my current knowledge I guess that the most optimal solution would be to use the SerializeField attribute but it may be you know better way to do that : pp
If that's a general problem with engine u might try #π»βunity-talk
Ok thank you It's just a problem with when I load up a project I'll look somewhere else
Please don't cross-post.
I don't know if you can do it at runtime. If you can, something like Rewired is the way to do it. Otherwise, use the modern #π±οΈβinput-system that replaces the Input Manager.
yeah then i have to setup the new one sad_cat
Hey, I am a 14YO trying to work out how all of this works haha, struggling with C# and was wondering if anyone had any tips on how to start out
There are lots of tutorials pinned to this channel, just start with the one that looks most appealing to you
thank you π
Second camera wont work, black, not even the blue background colour, just black not working, I am using urp, I want to make a camera act like a TV picking up a picture from somewhere else and using the texture to put it elsewhere, but the second camera doesnβt work
As soon as I delete the for camera the second one starts working
I know this happens to hdrp
But not urp
Only one camera can render to the screen at the same time. Unless there's camera stacking used. Otherwise, you can have several cameras rendering to a render texture.
how would I access a value in a game object's script from a prefab's script? I'm doing a flappy bird yt tutorial where the pipes are a prefab and I'm trying to access the variable 'birdIsAlive' in the bird game object's script from the pipe prefab's script but it says null reference when i try play the game
show the error and console
what is line 22
my editor doesnt say the lines so give me a sec
your birdScript is null
line 22 is the one highlighted here
also, you don tneed 2 separate variables
you can store prefab in public BirdScript bird
and then just instantiate that prefab
the prefab is stored in a completely different game object
called pipe spawner
if I'm misunderstanding something here its because I just started, sorry
You need to reference the bird when you instantiate the pipe with this pipe movement script
how would I do that?
!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.
Show where you're instantiating the pipe
Usual pattern would be cs var pipe = Instantiate(pipePrefab); pipe.birdScript = birdScript;Assuming the class that spawns the pipes have a reference to the bird via bird script.
ah ok I'll try that ty
Reminder that you can reference an object in the scene by their specific component type. You can always access the GameObject and Transform components using the properties gameObject and transform from any component - unless you're explicitly needing nothing other than a reference of the GameObject or Transform.
So is there another way?
Okaj I hope I have all the code here: https://gdl.space/kolagekaki.cs
When you right click a Weapon, it checks if one is already equipped and unequips it, then equips the new weapon.
This works through the event system, but it's somehow messing up my visual equip part, where it will visually unequip the weapon after equipping the new weapon.
The stats on the new weapon do work though.
Not sure where I'm going wrong or what to look for, are my events just triggering in the wrong order or something?
Hello, I tried using 2023.3.0a18 today and I got this message as I opened the project, they stay there even after restarting the engine. Should I just ignore it?
just giving me a bunch of errors
you should not be using an alpha release of Unity in the first place
Yeah, I mosty use LTS I just wanted to try
2023 is dead. If you want to 'try' the latest use Unity 6 Preview
Alright thanks
Okaj I hope I have all the code here:
fixed it, how come the first example doesn't work but the second does when I'm just assigning the same value? (as far as I can tell)
use this site for share code (for future) https://gdl.space/
ok thanks
My current inventory logic requires an item to know which inventoryslot it is in, but also requires the inventoryslot to know which item is in it.
Is this logic bad or wrong?
My reason behind it:
- I save and load items on my server, but not my inventory, so when loading items, each item needs to know which inventoryslot it was in.
- I can drag items between inventoryslots, so when I drop an item on an inventoryslot, that inventoryslot needs to know if there is an item in it already and then move that to the new item's old inventoryslot
how do I toggle Intellisense in visual studio community? (NOT visual studio code)
!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)
Tools->Options->TextEditor->C#->InteliSense
tysm
It's okayish. Sometimes you can't avoid it.
But you could consider some refactoring to change that:
- instead of saving the items, save the slots data, including the items.
Ideally you want to maintain a hierarchy of one way references like below, but sometimes there're just gonna be exceptions that break the rules.
Container(character, chest, box, etc)
Inventory
ItemSlot
ItemInstance
ItemDefinition(type)
Effect
Etc...
how to I get unity code completetion? it's only showing for the normal C# stuff
Share the video as mp4
Yep, that's not configured. Did you follow all the steps from the guide above that the bot shared?
yea I mean by configured you mean while installing vs code, also install the unity thingy right?
No. Carwash specifically invoked a bot reply for you here:
#π»βcode-beginner message
oh, sorry about that, i'll look into it rn
Hello everyone, I'm a student and right now I'm working on a project to create monopoly game but I encounter some problem when following this tutorial.
https://www.youtube.com/watch?v=iy-63zudcJ0&list=PLDcwWgfSSwTgIgtBkSn3lSFjzJQOxbr5E&index=6
here I provide a preview of my project.
#ΰΉΰΈΰΈ£ΰΉΰΉΰΈΰΉΰΈΰΈ΅ΰΈ’
ΰΈΰΈ±ΰΈΰΈΰΈ² ΰΈΰΉΰΈ§ΰΈ’ :
- Unity 3d
- Visual Studio Code
ΰΈΰΈ²ΰΈΰΈΰΈ²ΰΈ£ΰΉΰΈ:
Ipad air 3 + apple pencil 1 + Procreate
ΰΈ§ΰΈ΅ΰΈΰΈ΅ΰΉΰΈ ep ΰΈΰΈ·ΰΉΰΈΰΉΰΉΰΈΰΈ₯ΰΈ’ΰΉΰΈ₯ΰΈ΄ΰΈͺΰΈΰΉ : https://www.youtube.com/watch?v=nwA17CsjlGw&list=PLDcwWgfSSwTgIgtBkSn3lSFjzJQOxbr5E
ΰΈ§ΰΈ΅ΰΈΰΈ΅ΰΉΰΈΰΈΰΈ΅ΰΉΰΈΰΈ³ΰΈΰΈΆΰΉΰΈΰΈ‘ΰΈ²ΰΉΰΈΰΉΰΈΰΉΰΈΰΉΰΈΰΈ΅ΰΈ’ΰΉΰΈΰΈΰΈ²ΰΈ£ΰΈΰΈ±ΰΈΰΈΰΈ²ΰΉΰΈΰΈ‘ΰΈΰΉΰΈ§ΰΈ’ unity ΰΈΰΉΰΈ²ΰΈ‘ΰΈ΅ΰΉΰΈ§ΰΈ₯ΰΈ²ΰΈ§ΰΉΰΈ²ΰΈΰΈΰΈ°ΰΈΰΈ³ΰΉΰΈΰΈ΄ΰΉΰΈ‘ΰΈΰΈ°ΰΈΰΈ£ΰΈ±ΰΈ
I copied the entire documentation step by step and I still can't get the intellisense for unity elements T_T
Okay. Share a screenshot showing unity workload installed in vs and VS selected in external tools as the code editor.
This tutorial you're basing your code on is terrible, it's using very poor practices.
I think you should find a better one, or build your own system.
There is no reason to be using Rigidbodies for a board game
And if you are using Rigidbodies, MovePosition should never be used in Update.
It's just a mess all around.
sharing the 2nd one sec...
uhh what do you mean by unity workload there was no such thing in the documentation..
holy moly
there are more sections...
im so dumb
really sorry!
How would I reduce the brightness of a scene when the player loses? So I can make the 'game over' popup more bright compared to the background
The simplest approach is probably to overlay a semitransparent UI Image over everything
oh ok thanks
Is there any attribute to exclude and strip methods that this attribute has been attached to
For example [EditorOnly]
Do you have recommendation tutorial?
Brackeys ig
I am trying to make a Physics based controller for a Momentum based Platformer game but when I press the Jump Key it only SOMETIMES works and after I move around it basically stops working all together
No. That's what the prepeocessor directives are for.
sounds like a problem with your code
but it's not really for super advanced things, its only for begginers and to purely to understand the engine and coding
https://pastebin.com/HVC1Ctxj
EXCATLY Why I am posting the Code HERE for Help
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.
how can i reblind a control in unity i downloaded the new input system
Not entirely sure, but here you go https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute?view=net-8.0
Alternatively, you can just wrap the method in
#if UNITY_EDITOR
// Code
#endif
don't crosspost. and start by googling it, you might find that there are plenty of resources that tell you how
you're handling input in FixedUpdate
input needs to be handled in Update
Also your AddForce is commented out for jumping
okay
I know that, it was for testing if it was READING the input
you should not read input in FixedUpdate
Hi,
Sometimes when I follow some tutorials on YouTube, I see some variables start with an _. Why ?
It's a convention some people use for private fields
Private instance fields start with an underscore (_) and the remaining text is camelCased.
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names#naming-conventions
public class VazioRoxo : MonoBehaviour
{
public Transform playerdir;
Transform ball;
float distance = 0f;
float cooldown = 0f;
private void Start(){
ball = GetComponent<Transform>();
}
private void Update()
{
if (Input.GetKey(KeyCode.Z) && cooldown == 0f){
cooldown = 300f;
distance = 0f;
ball.position = new Vector3(playerdir.position.x, 0, playerdir.position.z);
}
if (cooldown <= 300f && cooldown > 0){
distance += 1f;
cooldown -= 1f;
ball.position = new Vector3(playerdir.position.x + distance, 0, playerdir.position.z);
}
}
}
@wintry quarry
My cube is only moving one way. How would I make the cube move according to the player's direction?
SO yeah your code is just always moving it on the x axis
What's the goal here
because there's a lot wrong with the code here
it's not just that it will "only move in one direction" right now.
It's also going to sort of be "attached" to the player.
It also has a problem of being framerate dependent.
Is the goal to shoot a projectile that will be independent of your player after firing it?
Also which object is this script attached to?
Cube(1)
Yeah
when i reblind the controls the controls won`t change
and the player is still moving with old movement this is my code for the player
and this is in the inspector
like "the cube attached to the player's head"
you'd have to show how you're doing the rebinding, but most likely your problem is you are rebinding a different instance of the action asset than the PLayerInput is using.
Each PlayerInput creates its own independent copy of the InputActionAsset
you would need to get that instance via InputActionAsset rebindMe = myPlayerInput.actions;
ok so the projectile itself?
Which is... just an object in the scene?
Use words
yes
can someone recommend a tutorial series? unity pathways ain't working for some reason
same server error every time
Ok so can you answer my questions about what your goals are with this script?
my script is inside it
where should i put it ?
nowhere in particular, I'm communicating a concept to you
do you understand what I mean?
your code that rebinds the input actions needs to be doing so to the correct instances of the actions
This projectile will be fired according to the player's vision

ok so basically you would need to do the following:
- When the button is pressed, record the player's forward facing direction.
- from there on, move in that direciton.
Something like:
Vector3 direction;
float speed = 10;
void Update() {
if (Input.GetKey(KeyCode.Z) && cooldown <= 0f){
cooldown = 1f;
ball.position = new Vector3(playerdir.position.x, 0, playerdir.position.z);
direction = playerdir.forward;
}
cooldown -= Time.deltaTime;
ball.position += Time.deltaTime * speed * direction;
}```
Hello, is there a way to compare the value of a variable in one frame to the value of the same variable in the previous frame because it's changing based on the player's input.
What's the goal here? It's usually better to do just do something when it changes, rather than trying to retractively detect the change
to do it the way you are asking, you would need a separate variable
yeah i`m doing this but not working
I'm working on the 2d player controller, and using the Mathf.MoveTowards, now when i change direction the player slides so i was thinking maybe if the direction (axisRaw) changes from 1 to -1 or the opposite i would change the rate of MoveTowards to the max speed of the character
you'd have to show your code for rebinding and how you got the reference
you're saying it slides now or you want it to slide?
i`m using this
Yes those are scripts. You would have to show the code
that's just a sample they provide
it's meant to show you how rebinding works
not really meant to be plugged & played directly into your game
Now, i don't want him to slide
You would have to show your code
You said you're using MoveTowards but that's really vague
it's unclear what you're using it for
This literally
So do you want acceleration or no?
Yeah but when it comes to changing direction, i don't want the character to go through acceleration and deceleration, i just want him to keep going
You could maybe do something like:
if (dir != 0 && Mathf.Sign(dir) != Mathf.Sign(speed)) {
speed = -speed;
}
speed = Mathf.MoveTowards(speed, dir * maxSpeed, Time.deltaTime * .3);
rb.velocity = new(speed, rb.velocity.y);```
a bit of a hack
kind of a strange movement you're describing
It worked, but the projectile follows the player's direction
Yeah that makes sense to me
Well i got it from watching videos but alright
@wintry quarry
you'd have to show your up to date code
if (Input.GetKey(KeyCode.Z) && cooldown == 0f){
cooldown = 300f;
distance = .5f;
ball.position = new Vector3(playerdir.position.x, 0, playerdir.position.z);
}
if (cooldown <= 300f && cooldown > 0){
cooldown -= 1f;
distance += .5f;
ball.position += playerdir.forward * distance * Time.deltaTime;
}
you didn't follow my example code
follow my example code and it will work. In my example, I stored the direction in a variable when launching the cube and used that.
it is similar
Your code is just doing playerdir.forward always, which results in this problem
it is different in ways that matter
it worked out
thanks
hi, i'm trying to add an image to my assets folder but my mouse turns into this π«
how do i fix it?
does right click import new asset work?
it does, thank you
I want to try making a screen wrap like this, but I want to customize the wrapping boundaries manually instead of relying on the camera size. Anyone know a way to do it? https://www.youtube.com/watch?v=zWy29yeFNX8&t=43s
Unity Basics - Screen Wrapping
Be sure to check out my Unity for Complete Beginners course on Udemy here: https://www.udemy.com/course/learning-unity-and-c-for-complete-beginners/?referralCode=23B51187C8A97B78D1CF
In this video I will explain how to setup a simple screen wrapping script that will allow you to have objects go off of the edge of...
im a bit confused. the first methods work like a charm, but when i do it in a foreach it doesnt seem to work. does someone know why?
what i want to do is to change the layer of every child
GameObject is not a component
you need to use
foreach (Transform t in transform)
to get all of the children
public static void SetLayerRecursively(this GameObject obj, int layer)
{
obj.layer = layer;
foreach (Transform child in obj.transform)
{
child.gameObject.SetLayerRecursively(layer);
}
}
i use this extension method to set the layer of a gameobject and all of its descendents
thx
Just replace the camera bounds with world space coordinates. If you still want it to be relative to the camera, just add the cameraβs position to your wrapping boundaries.
with this line private List<IDataPersistence> dataPersistenceObjects;
that's a declaration, have you assigned it to anything
That's where you declare it. Where do you set it to anything
Where do you create a list
What if I want to make it follow the player?
if I wanted to make a jump buffer should I use couroutines or time.delta
You are calling LoadGame before you set the list
you call loadgame before you fill the List
when i try to copy your code, it gives me an error at "this" with "Extention method can only be declared in non generic, non nested static class". you you know why?
yes, an extension method can only be declared in a non-generic, non-nested static class.
hmm, thats tough then, bc it needs to be IInteractable
mate, it's an extension method
if you don't know what that is, start by googling those words
Why? It's an extension method
You're adding a function to every game object
Then replace the cameraβs position with the playerβs positionβ¦
On unity when I call an api I receive a string of base64 audio that I should then convert into an audioclip, I tried to use the method WavUtility.ToAudioClip(base64string) but the problem si that it parses only files that were WAV or PCM.
In my case the audio that arrives is MP3, is there anything else I can try to convert it?
Ok, I'll try
ah, now i get it
u can put the function in any static class and then call the method from w/e other class u want.. (ones w/ IInteractable) for example
I was doing this tutorial https://www.youtube.com/watch?v=SsckrYYxcuM and after the first part when the script is done at 4:01 the guy in the tutorial can slide and i get this error anyone know a fix? my sliding script is attached
ADVANCED SLIDING IN 9 MINUTES - Unity Tutorial
In this video, I'm going to show you how to further improve my previous player movement controller by adding an advanced sliding ability, that supports sliding in all directions, sliding down slopes and building up speed while doing so.
If this tutorial has helped you in any way, I would really ap...
seems pretty clear
the error says exactly what the problem is
im just not sure how to fix it ._.
not PlayerObj
Your scirpt is on the PlayerObj object
The Rigidbody is on the Player object
You therefore can't just do GetComponent from your script to get the Rigidbody
why is the scirpt on PlayerObj instead of on Player?
my sliding and playermovment scripts are on player
You can also do playerObj.GetComponent<Rigidbody>(); but goddamn if that isn';t some confusing ass variable naming lol
prove it
the error message says otherwise
Click on the PlayerObj object
see what scripts are on that
I bet you also attached the Sliding script there
oh...
then you've mixed up references.. you've asked to retrieve a Rigidbody from PlayerObj
remember the error messages don't lie. If they're saying something, take them seriously
Hi guys, i'm making a mobile 2D golf game and the script of the arrow is not working correctly, its not showing the arrow on screen when player drag the ball... i cant send the code here because of the size but can anyone help me?
code link https://hastebin.com/share/ivomuqahap.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
!code u can use third party websites to share the code w/
π 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.
no console errors or anything? or just missing arrow?
no errors or warnings, just missing
check that
- ball transform is assigned
- the arrow has a renderer and is setup correctly and is visible when active/enabled
- ensure arrow is not being rendered behind other objects (check/adjust its Z positioning or sorting order)
- debug.log every step of the script to make sure inputs are acting accordingly..
case TouchPhase.Began:
Debug.Log("Touch Began at: " + startTouchPosition);
case TouchPhase.Moved:
if (isDragging)
{
Debug.Log("Touch Moved. Direction: " + direction + ", Distance: " + distance);
}
case TouchPhase.Ended:
case TouchPhase.Canceled:
Debug.Log("Touch Ended or Canceled");
break;```
Go into Playmode and while its running select ur arrow and everything and see if its present where it should be.. if its visible.. make sure its scaled and facing the right direction, etc.. i don't see anything that jumps out as being wrong necessarily
{
JumpBufferTimer = JumpBuffer;
} else {
JumpBufferTimer -= Time.deltaTime;
}
if (JumpBufferTimer >= 0){
RefRigidBody.velocity = new Vector2(RefRigidBody.velocity.x, JumpStrength);
JumpBufferTimer = 0;
}
if (Input.GetKeyUp(JumpKey) && RefRigidBody.velocity.y > 0f)
{
RefRigidBody.velocity = new Vector2(RefRigidBody.velocity.x, RefRigidBody.velocity.y * JumpDamping);
}
RefRigidBody.velocity = new Vector2(RefRigidBody.velocity.x, JumpStrength);
```
```private bool IsGrounded()
{
return Physics2D.OverlapCircle(GroundCheck.position, 0.2f, GroundLayer);
}```
anyone know why my character is able to jump in the air?
either it thinks its grounded.. or ur jumpbuffer allows it to jump
you debugged IsGrounded()'s return?
to see if its actually flipping true - false, i'd debug the jumpbuffer too
I'll check
once those things check out u can look deeper in the code to see if its something else
if this is in Update, which I guess it is, ithe code will run multiple times before isGrounded returns false
It can't be that as I can let go of the jump key and then hold it again and it'll still fly
why are u not using GetKeyDown?
I didn't write this code, a guy who I'm making this with did
getkey is odd choice for jump..
I'm just trying to implement a jump buffer
I checked everything, I make the change in code and now I got this error message in Unity, in visual studio the code has no errors
Quick question: Should I use the imported 3D asset itself or should i place the asset in the scene, unpack it and prefab it?
Show !code for ControleSeta
π 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.
if you do not see red underlines in vs code and you are certain that you have saved the code so that unity has compiled the most recent version, then you need to 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
well hopefully u just didnt copy and paste the entire code block i sent.. as the syntax was wrong.. i was just typing out some quick pseudo code to show where debugs could go
Also you do this
RefRigidBody.velocity = new Vector2(RefRigidBody.velocity.x, JumpStrength);
whatever the state of the key press and isGrounded. Why?
yea, the code block is iffy
^
I'm just trying to add a jump buffer and fix this issue
jumpbuffertimer is checked in the 2nd if statement w/o ever verifying if the player is grounded.. which would cause jumps to occure regardless
ah ok
u wouldnt even need a jump buffer.. tbh.. if u used GetKeyDown + a grounded conditional
if(grounded){
if(getkeydown) -> jump}
what
but u also said the ground check wasn't working correctly
so id probably sort that out first
yeah
Done
do you see errors in vs code now?
no, the original code still here
okay.. just making sure.. some people wildly copy and paste around here w/o noticing its not even full code
no, still no errors
still tryna find which step is this lol
after u install the unity development module, assign the editor in the external tools menu in unity, sometimes it requires u to "regenerate project files"
sometimes a restart helps seal the deal as well
ohh ur using VSCODE?
Microsoft Visual Studio?
ohh then yea, that pretty straight forward
is it vs code or visual studio. they are separate programs
and if you are not sure, then screenshot it
<-- vscode
<-- visual studio
its configured π
what should i try now?
the error is still the same Control can't fall thru? If so show hte switch statement.
i dont see errors in the ide for the switch anymore
i'd use the editor to keep my eyes on the arrow object and chek its transform/scale/etc to try to work out where it is and why its not working (if ur still asking about why the arrow is missing)
yeah, i'm going to try change some values and see if it make any difference
ive always moved a Arrow Point object to track the mouse/touch position and then using a line renderer to draw a line from the ball/ to the arrow tip
havent tried manipulating scales and stuff.. my guess would be something along those lines are getting messed up
Hey I'm "new" to unity, You can see I suffered from common knoledge on this server already.
Finally going back here, And I wanna say, I installed visual studio, And I'm SURE I have the unity stuff downloaded. But I'm not completely sure how to check if it works.
I tried writing 'input' just. 'input'. And it didn't change color at all.
Shorter messege:
I'm sure I have unity downloaded but I'm not sure it works right now.
Is there any extra stuff I gotta do? Or do I just have to start trying to script stuff.
!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
firstly screenshot your complete IDE window
void OnTriggerEnter2D(Collider2D other) { if(Input.GetKeyDown(KeyCode.E)) { if(other.tag == "Gun") { Debug.Log("Works"); FirstFireRate = gunHolder.GetComponent<ShootScript>().FireRate; gunHolder.GetComponent<ShootScript>().FireRate = other.GetComponent<WeaponStats>().FireRate; other.GetComponent<WeaponStats>().FireRate = FirstFireRate; } } } why isnt this working
I installed unity, And then installed Visual Studio on the windows store.
in ur IDE its pretty simple to know at the top left corner it'll say either Assembly-CSharp or it'll say Misc Files
man i am such a failrue but why is this not working
the arrow is tracked to the ball, it appear on scene, but in the game not
lemme check
its probably behind the terrain
'not working' is a piss poor explanation of the problem
remove the image/ renderer from the ground (keep the collider) and then test
its not even telling me the code is not wokring
I don't think its working right. From how.. its diffrent.
i just want it so when my player is near this object with the tag gun it gives me a debug
nope, thats not configured
Oh alr.
why would it, there is nothing there to tell it to do that
same, when i go to play mode it disappears
make sure to go back and see if u missed any steps.. (off hand i can think of assigning the IDE in the External Tools section of Unity)
then maybe regenerating project files / restarting the IDE and Unity
im a bit confused
π€ interesting
look at your Debug.Log. It only tells you when it has worked, not when it hasn't
In settings it doesn't say anything about Visual Studio.
I think I need to mention it for unity to fully understand.
My editor like... Visual Studio or is there some sort of file in my project for that?
yes ur VisualStudio
The instructions on !ide tell you what to change this to
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'll check it out
It just doesn't show up
Then hit browse and find it
I am trying to start a basic "hellow world!" program but im getting an error telling me that an incompatible .SDK is being targeted. Im positive I have the right SDK installed but I dont know how to change which one my project is targeting. I also found some help online but for visual studio community edition and those steps dont apply for me. If i downloaded visual studio community edition and then changed the setting would that affect my vs code as well?
which version of Visual Studio did you install?
OnTriggerEnter2D is called once, when something enters the trigger.
Input.GetKeyDown is true for one frame, when you press the key down
I wish you good luck with the timing. And if luck is not enough, change it to OnTriggerStay2D or use Input.GetKey
and do you have the VS package installed in your project
2022 Community
and your Editor version?
Unity is 2022.3.22f1.
i am sorry, but how do i change the application
settings?
that's good. Screenshot your Package manager window
I dunno what that is
in Unity Windows->Packagemanager
works perfectly thanks
Preferences->External Tools
you should have this package.. and it should be updated
it says "there are no packages or features"
screenshot it
unity registry is where u'll find built-in unity type assets
can also use search bar to help u find it
Guessing thats wrong
alr I did do I just reset unity now or something
wouldnt hurt to re-open it
and see if ur visual studio shows up now
(in the list)
alr time to check
This is an insane amount of things to do just to be able to code, How do new people survive this?
well you only have to do it once
i set it up 3 years ago.. and ive never had to change it
newer versions of unity come w/ the Visual Studio Editor plugin thing already installed..
It appeared!
so if ur IDE has Unity Developer Tools. it just works out of hte box
Also my PC sucks enough for me to just not want to download the newer versions of unity
thats fair
Are there any game breaking bugs I should know about before I lock in?
Hello there! Can anyone help me with the little resolution problem I've got?
So I've got a 2D Camera with Orthographic view and when I switch between different resolutions in "Game" Tab, instead of streching it cuts the screen off
that is perfectly normal because the aspect ratio must be maintained
So what you saying it's not supposed to stretch automatically?
you'll need to adjust ur ortho size to fill in the letterboxs
@rocky canyon Do I change it inside of scene editor or via code?
u can do it either way.
but that's gonna work just for single resolution then
May I DM someone regarding help with a script to move my character position on button press?
ahh, its probably just because my background is soo much bigger than the camera
I think you didn't get what I mean
What's happening is when I'm changing the playing resolution (like I choose 1920x1080 or 1024x768) in the dropping down list, the camera doesn't stretch according the choosen resolution but it just cuts the objects instead
assuming i had things that fit perfectly it'd probably break too
there scripts out there that can calculate the ortho size needed to match the screensize
like, this is what happens when it's 1920x1080
and this is what happens if it's set to 1024x768
yea, ull probably need a script to caclulate the screen dimensions and change the ortho size to fit
but orho size will change both horizontal/vertial size
here what happens is only horizontality changes
Like it doesn't being stretched but just cut
Why not skip the dms and just get help here?
Very very unlikely you will find someone to help in dms
Sure. I just didn't want to clutter up the chat when other people are using it
It is what it is here for π€·ββοΈ
How do I correct this code line?
I want to show the arrow if the ball is not moving
== not =
Like I'm not even sure whether it's intended behaviuor or it's unity bug
Why are you trying to set ball.position to 0
When I first started I thought of it this way. == means "is equal?" Like a question. It has two signs, so two words.
While = means "equals" as in a statement. It is one sign, so one word
I dunno why that helped so much haha, but as soon as I thought of that, I never made that mistake again
you are misinterpreting what you are seeing. when you change resolution in the editor it does not resize your game window it just tries to fit the required aspect ratio into that window, hence the 'cut off'
So.. My issue is.. I found a tutorial with a script on how to enter a different scene by pressing a button on a door, but I don't want to enter a different scene, I just want to change my position (since it's a 2D game where the next room is within the same scene, but out of view)
public class NewBehaviourScript : MonoBehaviour
{
private bool playerDetected;
public Transform doorPos;
public float width;
public float height;
public LayerMask whatIsPlayer;
private void Update()
{
playerDetected = Physics2D.OverlapBox(doorPos.position, new Vector2(width, height), 0, whatIsPlayer);
if (playerDetected == true)
{
if (Input.GetKey(KeyCode.Space))
{
}
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.blue;
Gizmos.DrawWireCube(doorPos.position, new Vector3(width, height, 1));
}
}```
This is the script for pressing at the door
i don't want to, just want to show the arrow if the ball is not moving
@languid spire yeah, I understand that it does that, my question is why does it cutting it instead of streaching
b/c stretching makes stuff look like sh*t
Then make the suggested change
#π»βcode-beginner message
Which will actually not fix the issue, but get you closer
How do you intend to know when the ball is moving
So change the player's position. You can just set position to a place, as long as it doesn't have a CharacterController
because it wants to show you the camera view in that aspect ratio, it wouldn't be doing that if it stretched
But how do I do that? π
maybe try using a script to dynamically modify the ortho view
this the full code https://hastebin.com/share/osapebuhox.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Okay, so how do you intend to know if the ball is moving? Not even asking in code, but like, words. What is the thing you're going to check for to determine if something is moving or not
that's a good question, i don't know π€
If you can't explain what you're looking for in words, you're not going to be able to translate it into code. You'll need to come up with what "is the ball moving" actually means
There are multiple answers, you just need to decide what you intend to do and then you can worry about coding that specific one
I am trying to start a basic "hellow world!" program but im getting an error telling me that an incompatible .SDK is being targeted. Im positive I have the right SDK installed but I dont know how to change which one my project is targeting. I also found some help online but for visual studio community edition and those steps dont apply for me. If i downloaded visual studio community edition and then changed the setting would that affect my vs code as well?
alright, so, it's a golf game, how can i track the ball speed to get the values that i need?
@rocky canyon @languid spire
This script look like more of a workaround hardcoding thing.
Do I understand correctly, that this is THE WAY how it's done for every 2D orho-camera game? Or I've done something wrong?
Because if the script in the thread you sent me is an usual way to solve this "problem" and it applies 100% of time when you want to have different resolutions
then... why such an important and essential piece of camera functional is it just works like that by default, as out-of-the-box solution? there's like million of different clipping settings and whatnot but none of basic camera streching functional?
Well, how would you define "speed"?
if you were to measure a balls speed irl how would you do that?
getting an error saying this is null for some reason
i have an audio source on the gun already
You have another one (instance of that script) where it's not set
considering Play() isn't null, it must be the thing before it
it's 2D, so the position of x and y axis
oh ill check that out
How would you translate "position" into "speed"?
I think the better way of thinking on this is not the speed but if the position value is not changing I can say that the ball is not moving, no?
try dx/dt
So, if you want to detect this, you would need to know where it was and compare that to where it is
You know where the ball is, that's transform.position. Now you need to find a way to know where it was
Either:
- The object this component is on is disabled
- This isn't the audio source it's talking about
ok ill check that
I don't think I got your idea π€ why do I need to know where it was if I only want to display the arrow if the position is stoped? can you explain again please?
Still no luck @steep walrus ? Is this failing if you just try to compile it in the vs code editor? Did you try it in the Visual Studio editor as well?
Okay, let's pretend you don't need to know where it was.
How do you intend to know if the cube has moved using only the position it is currently at
im not very wellversed in 2D publications.. so i cn't say if they all do it a different way.. but its not a bug or anything.. soo people must have come up with a method of doing it.. (esp for mobile when ur dimensions may be different from device to device)
With the start position of the ball on each level
its probably easier to start making a game w/ that in mind.. and it'd feel less like a work-a-round
Now doesn't that sound a bit like "knowing where the ball used to be"?
im just like opening a file and that popup comes up saying the wrong sdk is being targeted it says that x86 is incompatible with the c# dev kit and I found ways to retarget it but for visual studio community edition but when I try and do it there i cant figure it out even with a website saying step by step. regardless i would want to use vs code
I have an enemy that will chase down the player on a 2D plane and run a method when within x distance from the player. At first, I though about using Vector2.distance, but I'm worried about potential performance problems. If I had, as an example, 100 Vector2.distance calculations running per frame, would this cause any frame rate issues. If so, are there any alternative ways to solve this problem?
theres still a problem i have because when i do getkey it keeps switch rapidly
tryGetKeyDown instead
use GetKeyDown within OnTriggerStay2D
thats what i did :(
better to subtract the 2 positions and then use the resulting sqrMagnitude
Stay not Enter
this is what i did
With down it shouldn't go back n forth.. 1 key press 1 instruction
Then add a debug into the inner-most if statement body
Such as Debug.Log($"Triggered: {name} | {other.gameObject.name}");
in the one that checks for tag right?
inner-most if statement body
The one which checks for the key press
That's where all the logic happens and where you need a log
ooh, got it! I was thinking how can i code to get the last position from each shot
That would be one way to do it, and as I said, there are many. The important thing is picking one.
So you want to store the starting position, and check if the ball's current position is not equal to that
yeah, and then change the code because the arrow is hided all the time and I want to show it between every shot
Well I now have a problem, as even when its IN Update it still stops responding at all after a while
Update: For some reason it only detects when I am pressing space when i am moving on the floor
Why's my list isn't appearing in inspector?
Abstract classes aren't serializable
You can take a look at the SerializedReference attribute, might be what you need
Hey IΒ΄m new to C# and im stuck it feels like iΒ΄m at my plateu, everytime i get help with something from someone they always tells me to use more classes. because you can structure you code better this way. but i cant see how to use it. i know what it is and what it does( i think). but for me this only means that you are creating a mapstructure which in my opinion is the worst thing you can do to organise something. Can someone please explain to me when and why to use different classes. I think if i can understand this i can get over my plateu.
Perhaps you can explain what, in your opinion, is a better way to organise data structures
Find a few basic videos on OOP, after a few it should start to settle in with you
i dont know but it feels like everyprogram than is just a big mapstucture i thought the people doing programming languages would have thought about some better way. π¦ cause i kinda gave up my program cause i cant find my way inside my code without going back to the paper im doing the program from. and its not even big yet.
oki i thought i hade but i do it again π
Learn to use the IDE's navigational features, it's pretty powerful
so this
' mapstructure which in my opinion is the worst thing you can do to organise something'
is what? hyperbole? bullshit?
no its just a real life reflections, everything that i use in my daily life is a mapstructure and i hate it cause all you do is go through the entire thing every time you need to find something. if i need to find x in a-b-c-d-e-f-f1-f2-f3- etc its gonna take me forever. and in some of my ides the code needs to back up in the structure and if im on x and want that x to be inside c3 and c5 some where i need to go back to the start of the map and find where the hell i wanted it and where it came from.
I am new to coding and C#, is there someone who could give me a helping hand and recommend me some tutorials/videos i could watch to get into it
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello, guys! What's up? I have a question about an issue I am dealing with. So, my spotlight in my horror game that I am making isn't working properly when I have low or very low quality level. Check below the video to understand what I mean.
this doesn't seem like a code issue
I don't think so as well
Because my quality settings are working properly
You see how quality changes properly
this is a code channel. use #πβfind-a-channel to find an appropriate channel to ask your question in
First of all, I was thinking that this was a coding issue that's why I send that in here.
this you
and even if it were a code issue, you didn't bother even sharing the relevant code
but again, it does not appear to be a code related issue
Yes I am not sure 100% if it is or not but I think its not a coding issue
Anyway, I am going to send it there
@sage mirage Make sure to post actual details about what those option do and change.
I don't have any details thats the problem
Everything is working properly. My code seem to be fine without any issues.
Anyway, I am going to inspect it a little bit and if I won't find the solution to the problem I am going to post in #π»βunity-talk
I was creating a stamina bar for my player, i added the canvas and the image but when i try to drag the stamina bar image to the reference in the code, it shows the sign where it's not compatible. The stamina bar has an image componenet.
#π²βui-ux and post what exactly you are dragging and where
Little confused on how to do this properly. I have an image that I sliced up in the sprite editor. Each slice is a face of a cube. I have a mesh I created in code with uvs assigned for each face. How can I reference the sliced sprites to apply to the correct faces in code? I have a matreial on the meshrenderer, but if I slap the main sprite image in the albedo it applies the whole image to every face. It doesn't even let me drag a single slice there. https://gyazo.com/5b27732831ed6f892c56716ceaad23a2
Whats a good way to code stairs? I have a capsule collider with rigidbody movement and i want to be able to walk up small steps without having to jump. My only idea is to do some sort of special collider that tells the player to snap upward when its touched
The best way is to just fake it and having a flat collider with stairs as a visual
I was thinking of that too
I kinda wanna know how Rockstar games makes such good movement
You're not handling the input properly then. You need to capture the intent to jump in Update and hold onto it until FixedUpdate where you actually jump
can anyone help me understand the caution at the bottom of this object spawning page?
if my script inherits from NetworkBehaviour wouldn't it already have a gameobject property?
It's for assigning the network prefab instance, not its own object
They're just saying make sure you do myInstance.GetComponent<NetworkObject>().Spawn(); and not myPrefab.GetComponent<NetworkObject>().Spawn();
where myInstance was created with Instantiate()
ah I see that makes sense
so im a bit stukc here , im trying to get the enemies transforms for my turret script and im trying to find all of the enemies transform but im not sure exactly on how to do it with a list or an array
Why is this a loop
What's the point of setting targets to the same value multiple times?
im not sure , im trying to find all of the enemies transform π
So why are you looping over the targets list in order to set the targets list
What are you trying to set targets to
the enemies transform
also im trying to rotate the turret towards the enemy , how can i like do it
Asmippet of some code I have, maybe you can make it work for you
Vector3 dir = (target.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = Quaternion.Lerp(partToRotate.rotation, lookRotation, Time.deltaTime * turnSpeed).eulerAngles;
partToRotate.rotation = Quaternion.Euler(0f, rotation.y, 0f);
my targets var is a list lol
well you could apply the logic to a list of targets if you wanted, but that rotates a turret to look at an enemy
doe anyone know how to change the target .SDK of the c# dev kit in vs code. I found some guidance for visual studio community edition but it doesnt apply the same. I have been having some issues setting up my environment and im like 99% sure the issue is that an x86 .net sdk is being targeted instead of an x64. this is based off the error i have been getting
any ideas?
