#💻┃code-beginner
1 messages · Page 315 of 1
If it collides, what then?
by not working do you mean it just isn't doing anything?
Keep going until a full circle is reached, if theres no dash direction then no dash
have you used a Debug to see if that part of code is being reached?
yea the timer works fine i just want it to stop when the player enters the trigger lmao
Alright. That's what I'm referring to. How do you prefer to check the whole circle using raycasts?
also have you checked if you have changed the tag of the player? or if either objects have a trigger collider?
By the way you can also just construct the rotation once then just keep rotating the vector. Basically store the rotated vector and keep rotating it, rather than adjusting the quaternion and rotating the initial
Unity uses 6 digits after a number, so it's from 0 to 360 million Raycasts to be done
{
while (true)
{
float anglesChecked = 0;
while (anglesChecked < 360)
{
Quaternion axisRotation = Quaternion.AngleAxis(anglesChecked, Vector3.up);
Debug.DrawRay(transform.position, axisRotation * startDirection, Color.red);
//transform.rotation = axisRotation;
anglesChecked += _angleStepSpeed * Time.deltaTime;
yield return null;
}
}
}```
Heres the code. I just do 360 from the angle in a coroutine. (In the real code theres no coroutine)
yea i checked the player's tag is set to tag and the Is Trigger is set on
I think your best course of action right now is just using a Debug.Log() to see if the code is being reached
wait i think I found the issue
aight ill do that and try the issue i think its casuing thanks
construct the rotation once then just keep rotating the vector.
How would I be able to do this? I'm not very good with v3s and quaternions is it hard to do?
yep got it working turns out i had the script set in a different objects so it wasnt following the object with the trigger oops lol
This is unprecise and will affect the performance if wanted to be done more precisely
I'm sure it can be done with math
oh ok that makes sense, good luck with your coding journey!
It's the exact same as what you're doing now, but you store the rotated vector. Il type psuedo code cause on mobile.
Vector3 rayDirection = something;
Quaternion rotateDirection = Quaternion.AngleAxis(stuff)
...
rayDirection = rotateDirection * rayDirection;
noted, right now im having trouble getting it to do a radial check in the direction i want which is upwards. At the moment it goes around.
There is literally no solution that will avoid physics casts if they want it to not dash into colliders.
There most definitely is
I'm not sure what you mean by radial check in the upwards direction
Well goodluck trying to solve that purely with math, having no knowledge of the colliders around. Unless you want to manually calculate which area is free based off each part of a non primitive collider
Well, I'll try to come up with a solution when I am free
Also, "having no knowledge" about the colliders around is entirely false
Simply use SphereCast with the suitable radius
Well to simplify it, its just looking a direction that has a clear path like no walls or anything to move toward
some monsters in games have a quick side step move, its basically that
except in this case the enemy isnt limited being grounded it can go up or down
Ok so did you read the last part of my message? What is your plan when you have a giant wall or a completely unique shape like a half moon
I understand the case, which is why I think raycasts here is a fine solution.
yea im using that
im just trying to figure out how i can make this ray move along a different direction but i can try on my own
Simply find the maximum and minimum positions in the perpendicular direction of the distance between the centers
Ok so it's as I thought, there is no plan for unique shapes. This would cause the AI to possibly not dash into areas where it could
And if you try to deal with those cases, itll sure as hell be more expensive than doing like 8 raycasts.
my game is simple and uses simple structures that are square if the first check fails i place a cooldown on it regardless
why does unity allow me to do Quaternion * Vector3 but not the other way around?
It is not commutative, meaning ab is not the same as ba.
I often forget which order is the correct one, but at least theres an error if you try the wrong way.
A*B!=B*A
matrix multiplication is non commutative
i see
Ah discord formatting. It italicized my message lol
hey guys i want to set the time of my animation to the float value in the script how can i do this
Hey, sorry for reposting, feels like my question got a little burried, so Im asking again https://gdl.space/tacapodabe.cs
Script #2 creates a texture and applies it, but when I try to get textureCoords from the raycast in script #1 it always returns (0,0). Can anybody help me figure out why?
{
float anglesChecked = 0;
Vector3 axisV3 = Vector3.forward;
while (anglesChecked < 360)
{
Quaternion axisRotation = Quaternion.AngleAxis(anglesChecked, axisV3);
Vector3 direction = axisRotation * startDirection;
if (!Physics.Raycast(pos, direction, checkLength, obstacleMask))
{
return direction; // Found Direction
}
anglesChecked++;
}
Debug.LogError("Failed To Find Clear Path");
return Vector3.zero;
}```
Heres the final function
the teacher allowed help of ai and stuff so ive been using chatgpt to help me
void DrawCurvedLine(Vector3 startPoint, Vector3 endPoint, int pointCount)
{
GameObject lineObject = new GameObject("CurvedLine");
LineRenderer lineRenderer = lineObject.AddComponent<LineRenderer>();
lineRenderer.startWidth = 0.1f;
lineRenderer.endWidth = 0.1f;
lineRenderer.positionCount = pointCount;
Vector3[] points = new Vector3[pointCount];
for (int i = 0; i < pointCount; i++)
{
float t = i / (float)(pointCount - 1);
points[i] = Vector3.Slerp(startPoint, endPoint, t); // Adjust for sphere radius
}
lineRenderer.SetPositions(points);
}
but this code doesnt work as i want
it creates a curved line between two points i selected on the sphere but the line is inverted and the lines cull
https://docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html
Just to make sure, it is hitting a mesh collider right?
I would increase the angle by a bit, like 10 or 30. This would still be checking a lot of directions.
It is
Is the mesh readable? It should have read and write enabled
good idea thanks
Toggling convex off fixed it it seems
how 2 make 2d buttons dynammically?
in what way do you want to make them dynamically
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
public class DinoJumpScript : MonoBehaviour
{
public bool grounded;
public float speed;
public Rigidbody2D myrigidbody2D;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) == true && grounded == true)
{
myrigidbody2D.velocity = Vector2.up * speed;
}
}
}
``` ```using System.Collections;
using System.Collections.Generic;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
public class onGroundScript : MonoBehaviour
{
public DinoJumpScript script;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.layer == 3)
{
script.grounded = true;
}
}
}
``` Why the player can still jump ?
anyway, the main thing is that it works
you never set grounded to false. but also, relying on OnTriggerEnter2D is a pretty bad way to do a ground check, especially with the manual layer check like that
What is the correct way to do a ground check
physics queries like a raycast, overlapcircle, etc are preferred over physics messages
ok
how 2 make 2d buttons dynammically?
did you plan on answering this follow up question so anyone could possibly know wtf you are actually trying to achieve? #💻┃code-beginner message
#💻┃code-beginner message
i thought you said it works? yet your still asking the same question?
didn't i answered?
what you replied was not actually an answer to the question that was asked
they were not asking how you planned to implement that feature since, you know, that was the whole basis of your question. they were asking what you were actually trying to achieve so that an answer could be provided
i mean that i want 2 create it on runtime any way, but this way must work
just saying "2d buttons dynamically" doesn't actually say anything
creating on runtime?
what way, what do you want to do
didn't you know gr4ss, they want to create it on runtime
if you cannot describe what you are actually trying to do then you will not be able to get help since nobody knows what you are struggling to accomplish
Instantiate(myButton) run that twice, done
if i know way, i wouldn't ask
guy, it's genious
& can i through it use gameObject.GetComponent<Button>()?
sure?
or just instantiate of type Button, then you dont need to GetComponent
Hello, please advise what is the best way to implement multiplayer, if I want to implement a game in which the game state will be stored on the server, are there any tools?
Alot, but multiplayer is pretty difficult
I am using Mirror and it took me months to learn the basics and hook everything up to steamworks etc aswell
you'll have to research the available networking solutions and decide which fits your needs best. networking is not a beginner topic though. if you do not have experience with making a full game in unity yet, it is not a good idea to try to do multiplayer. but once you have chosen a networking solution you can ask for help in #archived-networking when you inevitably need some help with it
i worked with jmonkeyengine
before, but
well last time i checked jmonkeyengine is not the unity engine
yes, I just worked with it and it was possible to create headless server, and put logic into it but in unity i cant find information about it
there isn't just a magical "make a multiplayer game" feature in Unity. you need to research the available networking frameworks, choose the one that best fits your needs, then learn how to use that framework
I feel like now that i know more about coroutines i feel like Invoke is kinda useless, except maybe for when you have a very simple method. But other than that, the fact that you have to input the function as a string of its name for invoke, disallowing you from using method with parameters, just makes invoke useless, or am i missing something?
a lot of uselles information and service where you can create sh1ty multiplayer clone with juts sync
Is there really no option to create a headless server and override methods? onjoin onquit sendmessage etc
no, that's pretty accurate. another bad thing about Invoke is that it uses reflection to invoke the method, which means you cannot use local methods. there's also no proper compile time checking with invoking a method using Invoke since, like you said, it just uses the name of the method as a string
you are free to create this functionality yourself. of course you'll have to actually understand networking. otherwise stop ignoring what i've been telling you this whole time
ye but i guess mirror its just sync service and cant apply any logic right?
You can have a standalone mirror server or have a client host
As far as Im aware
I’m just asking if there really isn’t such functionality in unity, because in the damn monkeyengine you can run headless server mode, and override key methods,It's just strange that there is no such thing in Unity
you can create a headless server for unity. that doesn't mean you still don't need to choose a fucking networking solution that has the capabilities to do what you want
there are dozens of networking solutions you can choose from, you need to research them to find the one that best fits your needs. otherwise you need to do it yourself
we couldn't possibly know what is wrong with that little info. please see #854851968446365696 for what to include when asking for help
@slender nymph what do you mean by network solution
i mean a framework that does the networking for you because there is no built in multiplayer functionality in the unity engine. if you'd bothered to do any research about this, you'd know that
Do you really think that I didn’t search on the Internet?
it's pretty clear that you didn't
It’s obvious that I came here to ask people who have experience so that they could give me advice, and not just write blah blah blah you’re a s*cker and don’t look at the Internet for "Networj solution"
alright, this conversation is pointless. i'm going to block you now. good luck with your fruitless attempt at doing multiplayer since you clearly have no idea what is required for that
Where did you get this and how did you understand it?
Imagine calling 360 (or 36 or idk how many) raycasts
Do you read people's thoughts?
and?
it's really not that expensive
this isn't godot where a single raycast allocates like 600 bytes
have you done any profiling to determine if it is in fact expensive? or are you just assuming that big number == big performance hit
show your results then
I had about 80 enemies, each sending about 8 raycasts every frame trying to find player
didn't see any performance issue
Oh what, I'm supposed to magically pull out code that I removed and or heavily edited to improve perfomance?
For vision or what?
https://youtu.be/Xd4UhJufTx4?si=tmE9j7anPh8o90-U
you can watch this to get better idea
Find what common Unity optomizations truly make a difference. In this video I go over a bunch of interesting optimization tips as well and give you my recommendations on each.
Keep your code running fast with as little garbage allocation as possible by learning from these important concepts.
Benchmarks (let me know if you get weird results!):...
well you claimed to have actually profiled it to prove a performance issue. you made the claim, the burden of proof is on you.
I'm not planning on finding the code
It's already gone
and I won't bother proving you as I saw your previous argument
for finding the direction to walk and checking the player direction
You went so quick from telliong someone to search up networking solutions to blocking them
then what was the point of you coming in here about 360 raycasts?
Navmesh or rigidbody?
rigidbody
yes, i entertained their delusions for 20 minutes before i blocked them because they didn't bother doing any research about networking in unity and just assumed that they could just magically create a headless server with "onjoin" and "onquit" functionality
and it was HDRP
Finding directions using your solution is understandable
So you target high spec devices
they were zombies so I didn't need smart path finding
I was
I target low end so I have to optimize my code haard
I tried doing raycast culling and it was a horrible idea for me
what are you using raycast for
as I mentioned, culling. But that code is long gone as even on 256 raycasts the accuracy was bad and the fps was even more horrible than it was without it
I think I got like -50 fps just from rays on a for loop
Doing huge amounts off of raycasts should be done asynchronously in order to split the amount of rays that are shot out over a larger amount of time which should theoretically improve perfomance
which I have not done and it went horribly wrong
why using rays for culling
Physics culliong is slow
Trigger culling is way faster and I could replace my other system for cullingn with it
The best part about trigger culling is that it's just a trigger and objects have ontriggerenter and ontriggerexit methods in em
It's the fastest range and the best culling method if you don't want to have large floors disappear as the default camera cull spheres tend do to that
are you sure the problem is with the rays it self and not the thing you do with that info?
in pc, I don't think sending 300 rays would take more then 1ms. how slow can a low end device be?
doing 1000 raycasts takes no more than 0.5ms. 360 raycasts took under 0.2ms on average, it's really not that expensive
the expense probably came with either not using non alloc versions of queries that return multiple results, or whatever you were doing with the results
isn't the non alloc slower? it just prevents garbage
the garbage is going to be the biggest performance hit when the GC runs
but i can test what is faster real quick
but in a longer gameplay time
what I mean is the result would be even faster for a short test
Need help.
Trying to make a moving platform, and as internet said, easiest way to make player move with platform is to set platform as player's parent.
Everything works fine, but when i exit the "play" while player agent still on platform, editor gives an error:
"Cannot set the parent of the GameObject while activating or deactivating the parent GameObject"
What can i do with this?
it's a very minor difference that is almost not even worth worrying about, less than a tenth of a millisecond difference between 1k allocating and non allocating raycasts in a loop.
of course my test code allocated an array for each method call (but not each Raycast in the loop)
how do you set the parent? in update?
void OnCollisionEnter2D(Collision2D collision){
collision.gameObject.transform.SetParent(transform);
}
void OnCollisionExit2D(Collision2D collision){
collision.gameObject.transform.parent = null;
}
but we can safely conclude that the biggest hit to performance would be the GC when it cleans up all the garbage. this also doesn't account for when any colliders are found where the nonalloc overload will likely be faster since when the collection passed to it has fewer elements than the cast would have found when unbounded
OnCollisionExit2D is also called when exiting, it's kind of an annoying bug that unity does not consider a bug
i mean it Enter is called when you press play so i guess it kinda makes sense...
So, when i exit the playtest(? dont really know how it's called correctly) Unity fires OnCollisionExit2D event and tries to assign parent to player while being disabled at the same time?
yep. there's a Physics2D setting to prevent callbacksOnDisable just note that it affects everything, so that would include if you wanted to disable some object and get an OnXXXExit2D response at runtime too
Alright, will look for another way to do what i want, i guess.
Thank you big time.
unity told me that was "as designed" when i reported it as a bug a few months ago
how do I change the order in layer of a canvas button
UI draws based on order in hierarchy, move the object further down in the hierarchy to draw it on top of objects that are higher in the hierarchy
it is down in the hierarchy
well there's only one object on the canvas there so naturally its hierarchy order won't matter since that only affects how the UI draws
if you want to change how your ui appears with your world space objects then it depends on your canvas settings
this is not a code question btw
but again, it depends on your canvas settings
so Im trying to make it so that you can pick up and throw slimes in my game. issue: the slimes have this giant WanderAI script that is a state machine controlling how they move, and it seems to reset their position to before you throw it. Im just at a loss on how to fix 😅 script for WanderAI: https://pastebin.com/hGYR6U9m I can also share the scripts that pick up/drop items as well if needed
if you're going to use pastebin, can you at least select the language so there's syntax highlighting instead of just a giant grey blob of text
https://paste.ofcode.org/8N8DfMvdgUAGkbR2czKwhL --movement script
https://paste.ofcode.org/bdAW2xfsupdcxPA8DbfdVi --dash script
these are my code i have been using to create a dash function but its not working why ?
be more specific than "not working"
wouldn't it make more sense to have the dash inside of the movement script
it does this when i press dash dosent increase my speed
welp paste.ofcode isn't working for me right now so i can't even view the code 🤷♂️
same here
can i send you the code directly ?
no, just paste it to a different site
ok
https://gdl.space/ubukakecot.cs -- dash script
https://gdl.space/ruzafotida.cs -- movement code
okay so for starters, your SpeedControl method limits the movement speed
wdym where do i limit the speed can you highlight
your SpeedControl method
how do i fix it ?>
// limit velocity if needed
if (flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
this is where i limit my speed
how do i make a limit of 20 except of 10
could someone post tutorial videos on how to create a pursuer ai that will chase you down
Is it possible to set one Objects RectTranstform on the canvas to the same position as another objects if that other Object is in a Grid LayoutGroup?
The object I wanna move is on the same canvas but outside of the layout group
Vector3 limitedVel = Vector3.ClampMagnitude(flatVel, limit);```
Hi. So I've got a couple of places I think Static should be used but trying to use it sparingly. For example, I have a SceneLoader and I'm wondering if I make that static? Any ideas?
i would cheat by setting the object as the child of the one in the grid layout group, set the anchored Position to 0, then unparent. That might work
a float. Whatever speed limit you want to set
kk ima try it
is SceneLoader something that has to be in the scene?
like, is it a GameObject in the Hierarchy?
I feel SceneLoader just doesn't need any more than one instance in any context. It handles the software's level loading, stuff like transitions and initialisation
doesn't need any more than one instance? that's perfect for singleton
It is in DoNotDestroy
Yes, it is a singleton too
Well, yea. But I'm wondering if I can use Static too
what? by it being a singleton, it means you can already refer to it using the typename, like a static variable
It's fine, nothing criminal about leaving it a simple singleton
can i you make it so that my max walkspeed is always stuck on 10 and only when dashing it turns higher
you are using static when you use a singleton
Sorry I should be more speific, talking about Static fields and methods here
i see
i can't really see any real benefit or downside to it, so if you could, you can?
it's just odd since it's already a singleton
So for every script that uses Load, I of course need to get the SceneLoader script, which in Unity, is FindComponetByType()
Using static bypasses it
Better performance to my understanding
And easier readability
huh? but it's a singleton
are you misunderstanding how a singleton works?
you could just do SceneLoader.instance.YourMethod()
SceneLoader being the class type
Oh... yea
why do you need to get the SceneLoader script?
No no, I see how it literally is static now
Yep xDD sorry
it's good that you're thinking outside the box though, no harm in that
Static seems really rare use case in Unity then
happy devving
Thanks Wytea!!
Sorry if im stupid, but why does the target not registre hit?
When the target script is called "target" only, it works?
first you have an error
2, because you are probably using the name target in the other script instead of target1
why does this appear brbrbrbrbrbr
How do i keep my game from breaking whenever i press pause, then go to the mainmenu, then back to the same stage? I have this little tower defence game i am working on rn and i am veeeeery new to coding.
the object with this script doesnt have the GetWeaponItem script probably
or weapon is null
how does it break?
I have this little overview of all the UI and everything that has these values randomly selected. These values arent actually the ones i am working with, but i am using this as a sort of way to know that A. the game is not on and B. in case i run into the kind of bugs i have right now.
The game stays at this screen, no enemies spawn, i can build turret and pausing and retrying does not help at all.
so the game basically just doesnt "start"?
To grab different gun type scriptable objects in my game I just made a gun manager in the hierarchy with a simple script that holds all of the guns, is this frowned upon?
you got to do it somehow, as long as it works and its not too messy then its fine
Exactly! The game runs fine, i then go to the mainmenu from the pause screen, press play, it takes me to my level selector, i choose the same level and boom, its stuck, not playing at all
then you need to call a method that will reset the game and play it, or you already have one which you forgot to setup
I have a retry button that retrys the current level i am on but it does not work either?
tried to check if the weapon isnt null but welp doesnt work
uhhh, the error is on line 21, checking if its null and using it on line after wont do anything
what does the retry actually do
whats the logic behind it
line 21 is you getting the weapon I'm pretty sure
what , i dont understand waht you mean
whats the error with this code
is there an error?
because i see you changed the code actually
same error
This is what it does "sceneFader.FadeTo(SceneManager.GetActiveScene().name);"
so either equipmentManager or currentWeaponobject or weapon is null
put the public Weapon weapon another script i had that i could use
There is also a toggle () as well
and what does FadeTo do
oh damn
sure just plug in whatever the current limit is.
change it based on those other things.
You can do whatever you want in programming
just write it
It starts a Coroutine that is connected to some code that makes the scene fade in and out so it looks nice when you press retry or go to another level or the main menu.
so does it do just SceneManager.LoadScene()?
seems like weapon is null
the only one that didnt get printed
so make it not null, assign something to the slot
How do you the the black box around the code part? I can also post the code that is directly connected to the FadeTo thing!
for multiple lines you would do it a different 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.
Ah perfect
for just 1 line you would put ` at the beginning and end of the line
https://paste.myst.rs/tul12fst This is what my SceneFader script looks like.
a powerful website for storing and sharing text and code snippets. completely free and open source.
i did and the error still appears
before you set weapon, debug.log the thing you set weapon to
now after you set weapon, debug.log weapon
Where is even the 24th line?
Well, do you get what might be null ?
probably weapon
It's either equipmentManager or currentWeaponObject
Haven't we explained you the null issues a few days ago?
The newWeapon isn't null, because there's nothing trying to access its fields on the 24th line
Simply check the equipmentManager and currentWeaponObject, the NullReferenceExceptions are the easiest to deal with.
he already checked it
i alr checked if the equipmentmanager and currentwaponobject is null and they arent
Hey guys, I have an FSM and looking for some advice with my naming.
Firstly, the type FSM.State is a delegate. Then the properties of that type have methods assigned to them. I have State properties for Menu, Gameplay, Cinematic.. etc since this FSM deals with the game state.
So for the type name, State is okay, since it is a generalised FSM class.
As for the properties, I was thinking something as simple as "MenuState" or "Menu". But I've also heard "OnMenuState" is good since it implies there's some form of action (in this case a method) when it is the active state. Keep in mind, each state has functionaility for entering, on update and exiting.
Then the method, I would call "MenuState" too, which I obiviously can't, since you can't have the same names. So maybe "MenuStateMethod"? Or another could be "PerformMenuState" to imply activation of some kind.
Let me know your advice
Well, there should be no problem then 
Well,
-
- It's impossible, otherwise you wouldn't get an error
-
- You've literally shown that the
currentWeaponObjectisnullon the screenshot you've sent #💻┃code-beginner message
- You've literally shown that the
currentWeaponObject isnt null tho , its weapon
lemme check again
Well, they're both null, of course, the error is thrown
Have you seen the screenshot you yourself have sent? There's written that the currentWeaponObject is null
okay it is null

Well, of course
Distrusting the errors will make things a lot harder
Now you should simply make it not null 😐
Is this a load of gibberish?
how??
Well, I have to idea what you're trying to accomplish. Shouldn't you know it yourself..?
this is the target shooting, need it to work with script target1
Okay now i am gonna go crazy, my retry button doesnt work either. The timer does not start and enemies down spawn either....
Is
(SceneManager.GetActiveScene().name);
``` not enough to reset a level?
I would call them this way
public delegate void State();
public State menuState = MenuState;
public State gameplayState = GameplayState;
public static void MenuState() { }
public static void GameplayState() { }
It doesn't reset a level. It simply gets an active scene.
You'll have to reset a level by actually loading the current scene
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
this doesn't do anything
Also make sure it's included in the build
Alright boys the objective is simple. Get Visual Studio Code actually working with Unity. For years this thing has freaked out either with formatting or some other bullshit.
It's time to conquer it.
I have uninstalled VS Code and removed all extensions/settings.
We're going in clean.
I have a super entry level question if anyone has time on their hands to pm me, it's about a slightly annoying jump animation that I can't quite seem to get to play correctly.
Thats the even weirder thing though, i am using ```cs
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
But it just refuses to reset my scene
guys i have an image that is the child of a canvas ofc and when i did this it went to 0,0 of the world not the parent how do i fix that
Is your code actually running? Use Debug.Log to check
i want it to be 0,0 of the canvas
The scene also needs to be in the build index I believe.
Or whatever that thing is called.
localPosition
Ye the scene is in the Buildindex
Give me a sec and i will make a screenshot
Both codes are working
Wait dw turns out I'm him
Nope still doomed.
For some reason code I paste just refuses to get autoformatted like in Visual Studio.
And opening a code block doesn't create a new line before the first {
I know it does, but its not doing it automatically.
i'd hazard a guess that this could be configured
for c#
shift alt f
when I do some javascript work
you could probably set it to do so
it immediately autoformats regardless of any other input
Is there a easy fix to my issue of my player character having these weird ice physics? In which they won't stop sliding around weirdly?
increase friction?
Where do you find that? Rigid body?
yeah, in the material you set
This seems to cause another "action" to take place, so when I CTRL+Z it reverts to the un-formatted version.
Aka I need two undos to actually remove the paste.
You sure?
I could have sworn shit just works with JS.
Tbf, been a few months.
Might be gaslighting myself.
i mean, this isn't really broken
pasting is pasting, the setting just makes the paste trigger another action
It's just odd.
I would expect equivalent behavior across languages if the individual extensions for each language were doing their job.
just tested and yes it is a separate action
there's a split second where you can see the raw paste before it's formatted as well
And you have the auto formatting setting enabled?
i enabled it to test
Disable it and then try pasting.
it just does the raw paste
Really? Alright I must be losing it.
i mean, could be another extension you have
I did a clean install of VS Code.
Removed all extensions and settings.
well the format on paste is off by default as i showed in my screenshot
I guess I'm just confused because new programmers come into this channel, with screenshots of VS Code, and the formatting looks completely fine and they have new lines on code blocks. I assumed this was default behaviour given by the extension.
It is default behaviour, maybe you have an .editorconfig file that dictates other format guidelines and VSC bases itself on that?
VS and Rider both do that, if it finds such file in the project directory it overrides the format settings
hello i have a little problem and i dont know how to fix it. My Character dont jump but i dont see the problem in the code. I am a rly new beginner and i have no idea why its not working maybe one of you have time to help me and talk with in a discord speach channel .
So I'm not crazy?
Wat da fuk
there's a separate format on save thing
it's also off by default though.
Actually just to make sure. What's supposed to be default? Should it format on paste? New line for code block? What's expected?
you need some extension for editorconfig to work in vscode iirc
maybe you're just getting lucky with the snippets you witness? ive seen many instances of non-perfectly-formatted code throughout my experience as a helper in communities like these, albeit not in c# (i haven't been active here for long)
VS formats on paste, and adds missing using directives if required. It does log the format as an action, so you need to Ctrl+Z twice to undo the paste. As for editorconfig I have no idea
It's properly configured though, right? You get the completion list and errors underlined
oh right, vs is more common
i mean vs and vscode do look kinda similar if i recall correctly
Nah both have distinct default themes. You can pick them out.
true
Ya it's configured properly. I'm getting underlining, intellisense and auto complete.
Oh and get a load of this.
look at this for loop
just wrote it normally
I copy it
and when I paste it
auto format puts the new line in the for loop block
but when I TYPE it it does not
right, that's a separate thing
Do you have code style preference settings in VSC? They might be disabled
I am on a completely fresh install. Removed all settings and extensions prior to doing this.
But I will check, where can I find that?
alright one of these shmucks then
That would be the second one.
Before that can you test something out? Inside Update or any other method, hit backspace until you have no indentation left, then invoke a snippet (type for and Tab twice to insert it), does it format the whole thing correctly?
you mean like this?
Yeah and then inside the braces {} type for and tab twice
oh that's not good
I wrote for, and then the intellisense menu opened up
first tab closed the menu
second tab actually did a tab
snippets broken
Weird
this has been my life
with C# VS Code
It just seems to be completely broken on this PC
and I dont know why
but I do get this
and when I select it
when done in a properly formatted code block it does it right
Hm yep seems like it's not applying format by default. Trying on my side
I am sad
thanks
what is going on
Well for the braces, if I add a newline before opening them, it works.
Newline, open brace, enter.
But not open brace, enter
I've got that too.
Haven't found any code style setting so I think it's not shipped by default for VSC
Found a "format on type" setting but it does nothing, that's a bummer
Very similar to whar I have now, which is great. Question though, does that break C#'s standard convention?
No, I don't think it does
Since they're properties I thought it was PascalCase
But does the fact they're delegates override that?
Properties are supposed to be in PascalCase, but the two of type State are (1) not properties, and (2) even Unity does not capitalize properties (see: transform, gameObject, etc.)
It's pretty much freesyled in terms of naming conventions, but you do whatever you think is best
They're not properties, in the case I sent, so it's thisCase
That isn't a property?
public FSM.State MenuState { get; private set; }
That is one yes
This one is
It's a field when there is no accessors block after the name
Sorry may have not explained it, that is how they're syntactically written in my context
So then we run into MenuState and MenuState
In this case it should be called MenuState
Yes, I am aware unity doesn't but for this project I am abiding to C# standard
Good
You'll even get an IDE1006 if you name it menuState
Also this is definitely true. In my case it isn't but it is specific. If I had the liberty I would
Damn... Annoying. Yea, it's been bothering me, I can't think of a good name... Any more suggestions?
It's a pretty vital part of my gameloop which is referenced a lot, so it does really matter
Hmm... What about MenuStateRunning for the method
CurrentMenuState?If that's supposed to reflect the current menu state
Yea, that's a good one, although there isn't variation in menu states
So there is only one menu state
Hm why make a state machine for it then, if it never changes. Might as well make it get-only
No no, it has states. Just not ones speific to menus, only a single "Menu" state
So there is a Gameplay state, a Cinematic state, etc
Right so it's the "Menu" part of the name that shouldn't be there :)
What about this?
public delegate void StateCallback();
public StateCallback MenuStateCallback { get; private set; } = MenuState;
public StateCallback GameplayStateCallback { get; private set; } = GameplayState;
public static void MenuState() { }
public static void GameplayState() { }
No, because MenuState exists for the context of game menus
I don't follow. What class is this property in?
I haven't used or seen the word "Callback" before, what does that mean? Also yea, this looks great
My GameManager. Could be moved at a later date
Okay so MenuState is alright
Since it is a Game state, and it handles how the game behaviors
callbacks are functions that you give to other functions for that function to later call
stuff like how cameras, timeframe, certain graphics behave etc
Hmm... So my example is a Callback? a bit like cataclyst that makes other functions call?
So callback is something that holds a reference to the another method, which delegate does too and thus may be referred to as a callback
Like dominos or something... Am I right?
i haven't been following so i can't answer that
but no to the latter
Yeah, that's so
delegates are callbacks
callbacks aren't a syntactic thing, they're just a term to specify intent
I am having a problem in my game where my my player is floating when I start the game. I want my character to stay on the ground but I am unsure how.
if you've used stuff like ForEach or Map, the delegate you pass to those methods acts as a callback because ForEach will call that delegate to give info back to the caller
Where is the gravity for the character controller being applied?
@naive pawn @willow scroll @short hazel Thank you guys for the help
gravity for the character controller is applied in the Update()
specifically here in my script:
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
show the collider during playmode
What's the gravity?
yeah you're gonna have to send the !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.
In my script the gravity is:
public float gravity = 10f;
if (!characterController.isGrounded)
{
moveDirection.y -= gravity * Time.deltaTime;
}
nothing is wrong inside the script, there has to be issue with collider
make sure they aren't any invisible colliders
also no point of having capsule collider there, the character controller component is already a capsule collider
You know what.. its probably the skin width... since you're using isGrounded from the built in CC not an overlap/cast
So i just took away the capsule collider and tested the character controller on a different surface and the problem is still there. Here is more information about the scene:
also if it is skin width how would I alter the skin width so that I can resolve my issue?
look on the Character controller
play around with value but don't put it too low or might cause other issues
yep that was the problem. Thank you so much for helping me!
how would you go about making 2d square sprite to rotate its axis around? I dont have the project open but ive been meaning to ask.
right now the way my sprite VISUALLY rotates is through this code
Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 dir = new Vector2(mousePos.x - player.transform.position.x, mousePos.y - player.transform.position.y);
player.transform.up = dir;
but ive seen that when i run the game and i look at the scene menu, my sprite object doesnt rotate its axis at all. it just VISUALLY looks like its rotating. im trying to make it shoot bullets and for the bullet to match the sprite's rotation, but its going straight up
So how would i go about doing this?
That rotates. Maybe your Move Tool gizmo was in world space mode, in which case the arrows don't rotate at all?
And for the shooting you'll need to use transform.up instead of Vector3.up in the bullet direction calculation
Am I am doing anything wrong when I have about 20+ scripts on each object? moveable, health, shoot, spawnable, dockable, chatable, selectable, faction, ... and for each of them I have 3 scripts: model with the data, controller or presenter depending on MVC or MVP, and a view to any visual things.
now when I have 30 GOs in the view, I have 600+ scripts active.
Am I am doing something wrong? Is there any concern with being this deep into composition patterns?
how can i add text that tracks your highscore in my game?
Break the problem down.
- Add some text to the scene that would hold the high score value.
- Have a high score value that updates correctly relative to the current score
- Update the text when high score value changes
Maybe show what the error is
i figured it out
So when i open my project settings unity crashes
I doubt it's much of a problem but remove unused update loops from each component if you haven't. There is one optimization you can consider later and it's that is if you're doing GetComponent search through a single gameobject each frame it may be wise to group your components a bit more if possible, but unless you're running into hiccups I doubt it matters right now
Most of the comonents don't have an update() method. If the components don't have an update() method, do I still lose performance?
The only issue about having a large gameobject is using GetComponent on that gameobject as it'll have to search through all components until it finds one, so it can range anywhere from O(1) to 0(n)
but not likely to run into that issue unless you are making one of those large wave based games where you may be checking hundreds of gameobjects in a single frame
Unless GetComponent methods do use a hashtable but I can't really seem that specific information anywhere
Big-O is in terms of scale (at worst case) so it'd just be O(n)
Well, if someone can find me the docs that confirms this stuff since I'm getting different answers from the forums rofl
but either way, working with gameobjects with a ton of scripts a little hard for me. I like to keep them minimal if possible
I'm not worried about getComponent, I'm more worried about constant broadcast messages update etc.
if you remove Update method from your components it wont
Doesn't c# still have to inspect the monoscript to see whether it has an update method and, if so, call it?
Or is this done more efficiently?
[...] the order that the components are checked is not defined
sounds like it's not linear, so i'd guess it's O(1)
Was looking specifically if GetComponent uses a hash, or does it do some like linear lookup.
the presence of lifecycle methods wouldn't change at runtime, so i don't think it'd do the reflection every tick, instead being overhead on load/build
pretty sure it's liniear as C++ does not implement anything like the Dictionary class
Yeah, that's what I would expect, but I remember some forum posts that GetComponent does search in a orderly fashion but that wouldn't be the case with hash.
will have to test it to see who's lying to me haha
Can you please tell me why it doesn't work? Why it won't shut down.
What do you mean by shut down?
Well, it should be disabled by such a variable and the object should fall, but I have an object hanging in the air and the variable is not disabled.
So is that code even running? Debug it
Maybe the inspector isn't focused on the correct object or the lines of code aren't ever executed?
Some of the sites are working for some reason.
just keep it organized
dont stack 20 scripts in one game object
i usually make sth like
- Enemy
- Scripts
- Health System
- Loot System
- Scripts
everything nice and organized, 1 game object for 1 script
i hate crowded, unreadable inspectors
I'm sure it depends on what we're hashing, but Hashsets and Dictionary lookups only get more performant than a linear search through an array above 20ish elements.
If you have more than 20 components on a single gameoject you probably have other issues >_>
Hello all! A quick question. Should I learn Git using terminal? Or go with the desktop app?
go with whatever you want
weird type of question
whatever suits you
Hm I was asking if one is better than the other actually in terms of flexibility and such.
Up
GUIs don't always have the tools you need, but I hear Fork does provide a lot of what you can do with the console
but that's like 50 bux
I understand. Thanks a lot!
Like I have having problems reverting a specific file with GitHub Desktop so I had to do it through powershell
I am just a beginner so I just wanted to learn the one people use most.
Fork has an indefinite evaluation period
if I assign a struct in a component, am I passing a reference to the original?
Oh, does it? I may look into that then cause I'm curious what it provides
its like winrar 
Yep
Github desktop will be fine for what you need. You can always google the commands you need if there is truly something you need to do otherwise, I've yet to need to myself.
To me it seems easier since Its visuals! I may spend some time learning the terminal usage as well then.
I think I've done this wrong, I sent my whole project file to a friend, he gets this errror: Assets\Scripts\EnemyFollow.cs(28,19): error CS0103: The name 'BulletLife' does not exist in the current context; can't reassign the script, I believe is the way i shared the project. Any fix or way of sharing the project that would fix this?
How can you assign to something that isn't defined
whatever you got on line 28, it has no idea what BulletLife is
I used to only use the command prompt, swapping to a GUI was a night and day difference. No more spamming git diff because the GUI just has all the files and changes listed.
why isnt the master volume slider being selected?
void SelectOptionsFirstItem()
{
optionsButton.Select();
}
The method you posted seemingly selects a button, not a slider
Based on the variable names
sorry, poor naming
In this case, make sure the GameObject the target Selectable is on is active and enabled, at the time .Select() is executed on it
// bad, I assume
btn.Select();
btn.gameObject.SetActive(true);
public void OpenOptionsScreen()
{
mainButtons.SetActive(false);
optionsScreen.SetActive(true);
SelectOptionsFirstItem();
}
should be active
Do you have an active EventSystem in the scene? The source code of Selectable.Select() just calls EventSystem.current.SetSelectedGameObject(gameObject)
I do have an active select system
i've made it inline now and its still not working
public void OpenOptionsScreen()
{
mainButtons.SetActive(false);
optionsScreen.SetActive(true);
EventSystem.current.SetSelectedGameObject(optionsButton);
}
!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.
alright after figuring out the debugger I found an infinite code loop in lines 58 - 70
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i know it has to do with the for loops repeating themselves but i cant figure out how
(you didn't copy the URL after hitting "save" on the pastebin)
im a goober
Lines 62, 77: you increment i instead of n in your for loops!
The infinite loop occurs because n < userRuntimeDeck.Length always, since n does not change.
i love you 👍
@short hazel
void SelectFirstItem()
{
if (!EventSystem.current.currentSelectedGameObject) {
var child = mainButtons.gameObject.GetComponentInChildren<Selectable>();
if (child)
child.Select();
print(child.name);
}
else
{
if (!EventSystem.current.currentSelectedGameObject.activeInHierarchy)
{
var child = mainButtons.gameObject.GetComponentInChildren<Selectable>();
if (child)
child.Select();
print(child.name);
}
}
currentSelected = EventSystem.current.currentSelectedGameObject;
}
i had this code line
it seems to be selecting play then moving to the new gameobject?
even tho its called after the gameobjects are set active
public void OpenOptionsScreen()
{
mainButtons.SetActive(false);
optionsScreen.SetActive(true);
SelectFirstItem();
}
so i dont understand this
Hm I don't remember if SetActive() effects immediately, but if it only applies on the next frame, then the event system may still see the object as inactive at the time it's activated
that is critical
Can you try turning that piece of code into a coroutine, and placing a yield return null; before SelectFirstItem();?
selectfirst item or open options screen?
In OpenOptionsScreen, on the line before you call SelectFirstItem()
okay will truy
how do i get better at fixing my own bugs rather than waiting and relying on the responses of others?
public void OpenOptionsScreen()
{
StartCoroutine(OpenCoroutine());
}
IEnumerator OpenCoroutine()
{
mainButtons.SetActive(false);
optionsScreen.SetActive(true);
yield return null;
SelectFirstItem();
}
same thing unfortunately
cuz im stuck on this 1 frustrating bug right now but i dont want to take the time to record it, screenshot the code, and wait for people to respond to help me out.
it makes the whole process of just learning seem slow
keep practicing until you understand what you are doing enough that you can recognize the bugs you have created
so should i quit on this project or remake it enirely?
i mean i dont have that much done but is that the best i can do?
asking for help is part of learning. you can't get better if you don't learn from your mistakes. so if you just give up you won't have learned anything from whatever issue you are facing and will therefore not have had the experience of fixing it to rely on next time you face a similar issue
@short hazel okay even if i do a coroutine and wait for 1 second it still selects play what is happening 😭
Ah, because in SelectFirstItem you search components under mainButtons which is not where your slider is, from what I see of the Hierarchy
Can you try just doing like you had before with slider.Select()? But still using the coroutine
been working on a small 2d pixle art style game in unity for about a week now, I have a small map, player, idel, walking, jumping and falling animation, along with one enemy a slime, I also have a health bar, but since im still new ive think im not properly doing things, my game works but the health bar over the enermy isnt reacting to the player inpact, and its just static empty off the start. I have a couple of screen shots of all my, scripts and interactive sprites if somone would be willing to tell me what i could possibly be doing wrong and why this not working the way i want it too
guys ive made a rigid body based character controller and have added a slide mechanics that adds a constant force to the player when sliding. For some reason it doesnt conserve momentum the the player just stops after the slide. How to fix
@stuck palm
If that doesn't work, change how your system works. Add a script on the object you want to activate when the menu is enabled, and just add this in the class:
private void OnEnable()
{
if (TryGetComponent(out Selectable s))
s.Select();
}
This will find the first Selectable on the same object and if it exists, select it.
It's half past by midnight so I'm logging off, you can still ping me for updates but I'll see them later tomorrow (today? lol)
do you move the player using velocity?
does onenable work when you setActive?
Yes
i thought it just ran once
i'll try t that. dont i need to reference the event system though?
yes: void Move()
{
Vector3 currentVelocity = rb.velocity;
Vector3 targetVelocity = new Vector3(move.x, 0, move.y);
targetVelocity *= speed;
//Align Direction
targetVelocity = transform.TransformDirection(targetVelocity);
//Calculate forces on player
Vector3 velocityChange = (targetVelocity - currentVelocity);
velocityChange = new Vector3(velocityChange.x, 0, velocityChange.z);
//limit force (just in case)
Vector3.ClampMagnitude(velocityChange, maxForce);
rb.AddForce(velocityChange, ForceMode.VelocityChange);
}
Every time the script/object is enabled. And no, you don't need an EventSystem reference, it's handled by the selectable
this is the move function
Please embed !code as per the instructions below - this is very hard to read and not practical to copy-paste from!
!code
Ah, bot is ded
whats that?
#854851968446365696 has the same instructions
ii have no idea why the momentum isnt being conserved
is it because movement is interupting or sm?
A bot usually responds to this, but seems like it's asleep like I should be rn
where do you apply velocity?
is this for movement or sliding?
this is for movement
this is sliding: private void StartSlide()
{
sliding = true;
playerObj.localScale = new Vector3(playerObj.localScale.x, slideYScale, playerObj.localScale.z);
rb.AddForce(Vector3.down * 5f, ForceMode.Impulse); //adds downward force so player comes to ground quicker
slideTimer = maxSlideTime;
}
private void SlidingMovement()
{
Vector3 inputDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
Vector3 slideDirection = orientation.forward;
slideDirection.y = 0f;
//rb.AddForce(inputDirection.normalized * slideForce, ForceMode.Force);
rb.AddForce(slideDirection * slideForce, ForceMode.Force);
slideTimer -= Time.deltaTime;
if (slideTimer <= 0)
{
StopSlide();
}
sliding movement adds the force
trying to get into game development, had an idea for a game but no idea really how to make one, been spending the past week learning basics off youtube, one thing i can say, i will never hate on a game dev ever again
so your regular movement is also based on force and not velocity
you add force in the direction you wanna move?
what does StopSlide do?
yes
it just sets the scale back to normal
as well as set the sliding boolean to false
Okay big news. My reset button ACTUALLY works now but Going from being in a level, hitting pause, going back to the main menu, choosing the same level aaaaaaand it is still broken
No clue why xD
@short hazel still doesnt seem to work,
public class SelectOnEnable : MonoBehaviour
{
private void OnEnable()
{
if (TryGetComponent(out Selectable s))
s.Select();
print(s.gameObject.name + "selected");
}
}
i've made this class that selects on enable
applied it to my play button and my volume one, and it still doesnt seem to work
so extremely annoying for just a simple menu open
anyone else got a different implementation for menu changes?
Does it get selected when you click with mouse?
i cant click it with the mouse at all lmao
You cannot interact with the slider?
no not at all lmao
Can you post the slider’s inspector
is this what u wanted to see
Yeah.. first of all the using scale in UI is no-no, might be other invisible rect transform blocking it, but it shouldn’t stop you from select call 🤔
i know its so confusing 😭
might just use a home page from the asset store tbh
whenever I do
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "jetpack")
{
if (!isJetpackActive) { }
{
StartCoroutine(Jetpack());
}
}
if (collision.gameObject.tag == "gatesCam")
{
cam.GetComponent<Animator>().Play("Gates", -1, 0f);
}
}
it doesn't do anythin, and I am unsure how to fix it
The collider has is trigger on, the gameObject has collision components
If you make a new bare slider game object from menu, can you interact with it?
no lmao just tried
button doesnt get acrtivated eaitehr
hi could somebody help me with fixing my diagonal movement? its always faster then the horizontal or vertical movement
Okay then it sounds like a big image or something is blocking your click
Normalize the direction?
ig?
i have a fade canvas thing, but its not selectable so it shouldnt be an issue
its really that easy?
Either that or the image you have in the bottom of the hierarchy. Images may not be selectable but it still blocks UI raycast
i've turned off the raycast target
help I am trying to make it so that when I walk up to something and look at it and press "E" it activates an animation but I dont know howe to code it so that it activates the trigger I set up in the animation tab
my code:https://wtools.io/paste-code/bUEJ
the trigger is called "press"
Do you have a dynamic rigidbody on one of the objects?
Also, switch to .CompareTag("name") instead of .tag == "name"
Is there a reason on why I shouldnt organize my code to have 2 lines put together into 1 line?
Test line 1; test line 2;
rather than
test line 2;```
No.
Cool
You SHOULD have it as two lines
finally fixed it by doing this:
private void OnEnable()
{
if (TryGetComponent(out Selectable s))
s.Select();
print(s.gameObject.name + "selected");
}
private void Update()
{
if (EventSystem.current.currentSelectedGameObject == null)
{
if (TryGetComponent(out Selectable s))
s.Select();
print(s.gameObject.name + "selected");
}
}
dirty but gets the job done
Oh, misread that
Definitely have it as two lines
Is there a difference though?
Space saving is incredibly unimportant.
Readability is pretty much THE most important part of coding. Even more than performance to a certain point
Ok
And the former is WAAAAAY more readable than having stacked up variables for no reason
In this scenario, since both lines do similar things, I thought I could combine em (the top line)
To the compiler, there is no difference though
That is awful. No offense
fine, then Ill keep it separate
Always favor saving horizontal space over saving vertical space
I even split long statements vertically
ok
Im reworking my 214 lines of code to be more optimized and simpler to read
so yeah, just askin
Split it into multiple classes
That's the way to make it more readable and modular
I already combined the position and rotation thingy
they already are
still a lot of mess
Fair.
It's an ongoing process for sure
And a lot of it is ineffecient atm
Many lines of code that could be simpler being shorter
Hence why Im rewriting it with the new knowledge I have on what Im trying to achieve
I shouldve planned out my goal tbh
Keep in mind that lines of code and line length have no affect on actual efficiency at all.
The compiler is going to rewrite it multiple times anyways
It's only the personal efficiency of being able to read it
And understand it six months later
Well yeah, but keeping the lines shorter also helps with readability in a way
But yeah, refactoring as you gain new knowledge is gonna happen a loy
theres less area to look for
Ehhh, it CAN sometimes.
But often making things longer with more descriptive names and clear separation is more readable.
But then you can hit a point where is is just spaghetti of course
It's a balance
except it doesnt work in BUILLDDDDDD
I had this at first
grabbedObject.transform.rotation = grabTransform.transform.rotation;```
which I then changed to
```grabbedObject.transform.SetPositionAndRotation(grabTransform.transform.position, grabTransform.transform.rotation);``` since most of the 2 lines are the same anyway
Yeah, that is a fine change. I would write it like this usually
grabbedObject.transform.SetPositionAndRotation(
grabTransform.transform.position,
grabTransform.transform.rotation);
Which brings it up to three lines hahaha
Guess we view it differently
The way you just described would honestly make me more confused 😅
Yeah, once you have been doing it a decade or so, you just find that scrolling or jumping up and down is easy af, and panning horizontally is a pain
Or you might assume you know what the cut off code says, which is super dangerous.
I tend to use a lot of booleans when I dont have to
Like when I can just say example != null
rather than example == true
If sm1 doesnt mind can u pls see this
this has been bothering me for a very long time and I think its pretty basic
YouTube “Unity trigger colliders”
im not trying to make an object a trigger im tryuing to make pressing a button activate an animation trigger
A UI button?
you mean a Trigger parameter within the Animator?
no a key on my keyboard
you just access the animator and change the trigger..
ye I alr made the trigger
im js trying to bind it to a key
https://docs.unity3d.com/ScriptReference/Animator.SetTrigger.html
animatorReference.SetTrigger("MyTrigger");
if(Input.GetKeyDown(Keycode.Space){ ^ }
its giving me an eror
well whats the error say?
Then send the code
i did one sec
the error is the toilet variable hasnt been assigned but I assigned it in the inspector and its still not working
Public void Interact() won’t work it needs to be “public void Update()”
^ yea unless ur calling Interact(); in your update loop that code isnt even running
Update is a prebuilt function that gets called by Unity automatically every frame
changing its name broke that feature
ok but wait now it wants me to delete
interact()
I get that
but wont it make it so that pressing e activates the trigger
at any time
a child of the gameObject has a rigid body
that would require a bit more logic..
like a bool u enable when looking at it..
looking at it -> set bool to true
in update
if(pressbutton){
chck if lookin at it is true then allow code}
Then it won't work
Gotta be the object with the script, or the colliding object with the trigger collider
the animation sets
but now
the animation itself
is different then the one I created
and its breaking the object entirely
but I can see it transitioning in the animator tab
thank you for letting me know
i wasnt 100% sure on that
every time I press E the button I want the object js dissappears
I have an enum that I am using for the validation of chess moves::
public enum colorPiece { Dark = -1, Light = 1 };
if ((int)BitBoard.positions[position + (move * (int)color)].color * (int)color == 1)
{
valid = false;
}
the goal with the if statement is to prevent cannibalism, by getting the color of the piece in the projected square, multiplying it's color by the pieces color. If you get 1, [(-1x-1) or (1x1)] the move should be marked invalid before continuing on. this check works on the white pieces, but it doesn't work for the black pieces.
https://gdl.space/capilufugu.cs
the rest of the method if necessary
I swapped to directly test equality:
if (BitBoard.positions[position + (move * (int)color)].color == color)
and it still doesn't work, so it's not a math issue
debug.log the result and see what it is and what you want it to be
There is no way of modifying an audio clip speed straigh out in Unity right?
Cause I kinda need some audio to match out an animation on a very precise manner
Closest is adjusting the pitch.
Otherwise you need a 3rd party solution
can someone tell me why my mathf.clamp() isnt working properly
heres the link https://hastebin.com/share/lamifeluha.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
whats wrong with it
idk it just doesnt clamp the value
when i play the game, the value goes past 20
and when it goes into the negatives, it automatically resets to 90 degrees
What happens when you debug.log the newrotation float
heres the link to the code https://hastebin.com/share/vinoxapoge.csharp
here are the logs
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I am trying to make it so that whern I press E when my camera collider meets my object that it actives an animation in the already settup animator
I have set up a tirgger that activates the animation properly and am trying to get it when I press E when the camera collider meets the object that it activates the trigger
but for some reason it refuses to activate the trigger
https://wtools.io/paste-code/bUEN
WEB Tools
df csharp code
using System.Collections; using System.Collections.Generic; using UnityEngine; public class pooplol : MonoBehaviour { public Animator T
Image
pls help ive been trying for too long
I figured it out through debug.log
some pieces registered as light because the way I got the position didn't take into account the side the pieces start on correctly
Debug.Log($"New Rotation: {newRotation}");
uno secondo
nice, thats what debug.log is for
shows you what it is instead of what you think
sorry i wanted to try something else first
Does anyone know how I can fix this?
you need to give it a name
it
Give what a name
This doesn't seem to make sense
A friend and I have been working on a wall slide that occurs when you press against a flat surface of an object (wall), if I'm wall sliding on the rotation the object is facing, I wall slide just fine, but whenever I try to wall slide on any other wall that faces a different direction, the character goes crazy trying to face the object's orientation. Is there a way to take the rotation or orientation of the face instead of the object? Does anyone have any insights on how I can handle this?
no, ignore that
show the code !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Hm after some reading it seems C# does not support covariance for arrays..
You need to create a new array of GameActions, you can't just put the curly braces. var[] array = new var[] {a, b, ...};
It's a property though
Doesn't matter
You're specifying the default value of a property
So you need to actually create the array to put the values in
Tbh, that's the most convoluted syntax I've ever heard of
You mean create an array somewhere in the constructor and then assign that to the property?
Not really. You have to create the array, then you can give it values
You create the container, then you can use the {} syntax to populate it
[ItemNotNull]
public GameAction<IActionArgument>[] GameActions { get; } =
{
new AttackGameAction(),
new MovementGameAction()
};
How
new
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class next_level : MonoBehaviour
{
public TMP_Text text;
public GameObject m_clone;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider other)
{
if (other.tag == "NextLevelTag");
{
Debug.Log("Player passed through a pipe, score + 1 ");
}
}
}
Doesn't OnTriggerEnter2D need to be inside of Update()? Otherwise how else would it be called?
it gets called by itself, by unity
when the collision occurs
look at the suggestion in gray
What suggestion
It clearly says what needs to be changed
But that's an empty array
This section in the Player Movement handles the wall slide script:
if (wallCheck.wallD.z < 0f && currentMovement.z > 0f currentMovement.z < 0f && wallCheck.wallD.z > 0f currentMovement.x > 0f && wallCheck.wallD.x < 0f || currentMovement.x < 0f && wallCheck.wallD.x > 0f)
{
correctD = true;
}
else if (isMovementPressed){
correctD = false;
}
if (wallCheck.isWall && currentMovement.y < -0.1f && isMovementPressed && correctD && isFalling && !wallSlide)
{
wallSlide = true;
currentMovement.x = 0;
currentMovement.z = 0;
currentMovement.y = 0f;
// transform.rotation =
}
if (wallSlide == true && correctD == false) {
wallSlide = false;
}
And this one handles the Wall Detection for the player:
public class WallDetection : MonoBehaviour
{
public bool isWall = false;
public Vector3 wallpos;
public Quaternion wallrot;
public Vector3 wallD;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Wall") {
isWall = true;
wallpos = new Vector3(other.transform.position.x, other.transform.position.y, other.transform.position.z);
wallrot = Quaternion.Euler(other.transform.rotation.eulerAngles);
wallD = transform.forward;
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.tag == "Wall")
{
isWall = false;
wallpos = new Vector3(0,0,0);
wallrot = Quaternion.Euler(0,0,0);
wallD = new Vector3(0, 0, 0);
}
}
private void Update()
{
}
}
oh youre right
yea that gets populated by your curly brackets
Also, collider2d, not collider
But that's the same issue as before no?
did you fill in the suggestion to test it?
What suggestion?
thanks, i got it now, you're right
btw does anyone know why i get this?
Is this something you've actually typed in or a suggestion from your IDE you have not approved yet
It's @frosty lantern 's suggestion
I have a prefab named pipes and inside of pipes I have an insivisible boxcollider item On Trigger, which is supposed to Debug.Log on the terminal that the player has officially passed on to the next level and will print a message on to the terminal
But it is in your code, right? Not an autocomplete you haven't confirmed?
it shows up in your ide when you take a screenshot so if you didn't type it yourself your compiler is telling you how to fix it.
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class next_level : MonoBehaviour
{
public TMP_Text text;
public GameObject m_clone;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "NextLevelTag")
{
Debug.Log("Player passed through a pipe, score + 1 ");
}
}
}
delete the script from your object and add it again
No this is the current version in my script:
[ItemNotNull]
public GameAction<IActionArgument>[] GameActions { get; } = {
new AttackGameAction(),
new MovementGameAction()
};
Because of prettier
It automatically removes the unnecessary stuff
Then add in the thing the IDE is suggesting
There is nothing it suggests though
click on the gray text and press tab
Nevermind my IDE, can you just tell me the syntax that allows me to initialise those two IActionArguments please?
Can you show the type definition for AttackGameAction
Yes
public class AttackGameAction : GameAction<AttackActionArgument>
public class AttackActionArgument : IActionArgument
{
}
public abstract class GameAction<T> : IActionBehaviour<T> where T : IActionArgument
public interface IActionBehaviour<in T> where T : IActionArgument
for the sake of testing, maybe forget the auto property for now and see if you can throw those into an array you initialized
Type covariance only works for interface, not classes
Okay, so, I think the issue is that AttackGameAction takes specifically AttackActionArgument, but your list is expecting a GameAction that can take any IActionArgument? Essentially, your array is of a less specific typing than AttackGameAction
Type covariance only works for interface, not classes
What does this mean in my case. Those are both interfaces no?
I don't see how AttackGameAction is an IActionArgument at all Ah, I missed the wrapping type
GameAction<T> is not interface, so you cannot have it reference to covariance T
Wdym, it's just a generic no? There is no compiler warning anywhere regarding that either
List<object> x = new List<string>(); // wrong
IEnumerable<object> y = new List<string>(); // works
So how do I go from here
The Debug.Log thing doesnt work
I just want an array of multiple objects that inherit from GameAction and implement IActionArgument
That's all I'm asking for, C# 😭
One thing you can do, is for example using IActionBehaviour<IActionArgument>[] instead of GameAction<IActionArgument>[].
However you will have many limitations due to the nature of interfaces
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Xml;
using TMPro;
using UnityEditor;
using UnityEngine;
using UnityEngine.SocialPlatforms.Impl;
using static UnityEngine.RuleTile.TilingRuleOutput;
using UnityRandom = UnityEngine.Random;
public class Creator_Destroyer : MonoBehaviour
{
public GameObject whatIstoBeDestroyed;
private GameObject m_clone;
//public TMP_Text scoreText;
public float DestroyWhenReachesThisXPosition = -15f;
// Start is called before the first frame update
public float _timer = 0; //we need a time slowdown to slow the speed of generating new obstacles in our game
public float when_timer_should_stop = 2f;
Vector3 pipeSpawnVector;
private float speed;
private void Start()
{
cloneInstantiator();
Vector3 pipeSpawnVector = new Vector3(7.73f, UnityRandom.Range(-3.15f, 3.3f), 0);
}
private void Update()
{
Check();
_timer += Time.deltaTime;
speed = _timer * 2.1f ;
m_clone.transform.Translate(Vector2.left * Time.deltaTime * speed);
}
private void Check()
{
if (_timer >= when_timer_should_stop)
{
_timer = 0; //reset
Destroy(m_clone);
cloneInstantiator();
}
}
void cloneInstantiator()
{
float randomY = UnityRandom.Range(-3.15f, 3.3f);
m_clone = Instantiate(whatIstoBeDestroyed, new Vector3(7.73f, randomY, 0), transform.rotation);
}
/*
void Check_If_Player_Passed()
{
float localXPosition = m_clone.transform.localPosition.x;
if (localXPosition < -20)
{
float.Parse(text_score) += 1;
}
}
*/
}
Is there any way I could shorten this?
First keep your coding convention consistent
What is pipeSpawnVector for?
Is there a reason that spawner is responsible for moving and destroying? Otherwise you can split them into separate script and attach to spawned object.
I dont want it to attach to a spawned object
I tried that many ways and it always creates exponential amount of spawnable objects
Doesn't c# compile the code?
Unity just behaved differently after I swapped 2 lines of code that should be runnning at the same time
Code doesn't run at the same time, it runs line by line
Then what is compiled vs interpreted?
I though interpreted was the line by line one
all my sources say otherwise so Im curious about that
Not saying that I dont believe you or that you are wrong, Im just newish to coding
Are you asking this in the context of Unity?
I'm sensing your question has nothing to do whether or not c# is compiled or interpreted.
Anyway, does anyone know why this script that I got fails to debug.log that my player has touched the invisible line that is supposed to tell whether or not I went through a pipe?
Eventually this invisible barrier is supposed to let me know and update text automatically
Well, I know that C# is compiled, but the whole reading line by line part threw me off
Unity is single threaded, so it it will go line by line. You can look into DOTs if you need something otherwise, but that isn't something a beginner should even begin to consider.
me?
Ok
Ill do a bit more research on that though, seems interesting
btw this is the code...
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class next_level : MonoBehaviour
{
public TMP_Text text;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "NextLevelTag")
{
Debug.Log("Player passed through a pipe, score + 1 ");
}
}
}
does your player object have a rigidbody on it ?
is your collider on the next level line set to istrigger ?
On the level: yes, on the player: no
Are you new to coding? I highly doubt you need dots or anything parallel tbh. You should say what your actual issue is.
The level doesn't actually exist into my hierarchy. (It's in a prefab )
But Im no where near proficient with C#
This is about compilation, not how it actually runs. These are completely separate things
aight
Show the collider gizmo
The collider component was also collapsed, which is pretty unhelpful
and here's what it looks like if I turn the Sprite Renderer on
its a big fat pipe
Is is possible to get the information from a face's orientation of an object?
No need for the renderer component at all if it's invisible.
But anyways, is the player rigidbody dynamic? Or kinematic?
Put a debug log outside of the if statement and see if any trigger is happening. If it is, then i would ask if you have saved your scene since making that tag in the inspector.
Like the normal?
Dynamic
Yeah, something like that :>
I turned it Kinematic
and don't see a difference
Perhaps what is wrong is the way this OnTriggerEnter2D() is structured?
you should be using other.CompareTag("NextLevelTag"), but can you put a debug log outside of that if statement, run the game, and see if anything else is firing off ? like Debug.Log(other.name)
Also i could be wrong but it looks like the class name on that script doesnt match the class name of the file name
its fine just horrible convention
its pretty much the same except my convention
It MUST be dynamic
yeah I just realized that
But try .CompareTag I guess
it doenst move if its Kinematic
yeah im trying that rn, doesnt work either unfortunately
show me the file name of that class in your project folder, can you at least verify your start method can log a line out ?