#π»βcode-beginner
1 messages Β· Page 452 of 1
Hi all, looking for some code structure suggestions:
A player can pick up an item, and item ranges from [Ones you can throw, Ones you can shoot (i.e. a gun), Ones you can slice (i.e. a sword)...]
I have one ItemBehaviour script with all the interface that holds IThrowable IShootable...
Now the ItemBehaviour script will get length if I squeeze all the functions into one script I think, what's a better way of structuring it?
thanks
public class ItemBehaviour : MonoBehaviour {
private ThrowableBehaviour throwableBehaviour;
private ShootableBehaviour shootableBehaviour;
private SliceableBehaviour sliceableBehaviour;
void Start() {
throwableBehaviour = GetComponent<ThrowableBehaviour>();
shootableBehaviour = GetComponent<ShootableBehaviour>();
sliceableBehaviour = GetComponent<SliceableBehaviour>();
}
public void PerformThrow() {
throwableBehaviour?.Throw();
}
public void PerformShoot() {
shootableBehaviour?.Shoot();
}
public void PerformSlice() {
sliceableBehaviour?.Slice();
}
Maybe something like this? So the logic for the action sits within the Behaviour script?
Looking at a structure like this, I almost don't need to involve any interface?
you do realize that the ? operator does not work with monobehaviours
A mesh is not a GameObject or a component, it's an asset
Dyou assign it at runtime
And every time the mesh changes you would need to reassign it to the collider
sorry I didn't know that. Thought it would check if the variable is null or not
works for POCO's, not for Monos
gotcha thanks!
Involving interfaces would shorten up this code, since GetComponent allows interface types.
private IPerformable performable;
//...
performable = GetComponent<IPerformable>();
//...
performable.PerformAction();
but what do you do when you have multiples?
Interfaces allow inheritance, so you can make a interface IShootable : IPerformable if you want to add specific members for the more specific interface
Multiples?
multiple types of Performable on the same object, i.e An Axe is both Throwable and Slashable
That's not in the initial spec, but if that's needed my solution won't work
not criticizing your solution, it's one I use often myself, just pointing out potential drawbacks
thanks, this makes sense
how do i get rid of this annoying logo
turn the gizmo off
i tried turn it off here but didnt work
do i just turn all 3d icons off?
that seems to work
ahh okok, thanks
Can someone help with this issue I have, I can't seem to find a solution anywhere on YouTube or just on the internet.
I'm using a prefab called "Enemy" to spawn in a red cube guy with a gun, although, the script to control his movement needs the player's position so he can move over there. Issue is that I can't reference the player in the behaviour component in unity inspector because the player isn't inside the enemy prefab.
Chat, what's "delta"?
in what context
Here in my book it's in mouse input
the fourth letter of the Greek alphabet?
do you mean the "mouse delta"? because that is the change in the mouse's position per frame
if (Input.mouseScrollDelta.y > 0) {
so it's not even the mouse delta, it's the mouse's scroll delta. which is the change in the scroll wheel that frame
delta generally means 'change from previously reported value'
Thanks
if anyone could help me realise what im doing wrong in this script thats making the gun flip wrong that would be greatly appreciated.
basically i just need the sprite to flip when you get to a certain point in the rotation.
also i know the code is not clean at all dont worry about it just wanna get this working before i clean it up
also instead of manually constructing the rotations like that (which is wrong per the link i just sent) why not just use transform.Rotate(0, 180, 0) or just flip the sprite on the sprite renderer?
the main reason i dont wanna use the flip in the sprite renderer is because this script is on a "Weapon Slot" game object, allowing me to input any weapon as a child of the slot and it will still rotate and flip the sprite in the same way.
if i used the flip in sprite renderer it would only work for the current pistol and not any future weapons right?

using transform.Rotate(0, 180, 0) fixed this, thanks
ok, so I dont think eulerAngles or
I'm in this problem for days right now
can I maybe update my unity version or download another admob version will this help?
- this does not appear to be a code issue
- see the console for details
- #π±βmobile
okay sorry
Why cant i access a function?
When i press no function i see monoscript
then string smt
because you dragged it from the Project folder not the Instance
it needs to be on a gameobject
Its on a button
what can i do instead of
public Keycode slot1,slot2,slot3,slot4
switch (key)
{
case(slot1):
slot1.doshit()
break;
case(slot2):
slot2.doshit()
break;
case(slot3):
slot3.doshit()
break;
}
yh?
I dont understand
drag inside the slot the script thats on a gameobject , not the project folder..
use array of keycodes and a loop
and equate the key
aighty thanks
I did that
But it still doesnt come up
something like this
#π»βcode-beginner message
"stolen" from praetorblue
ye ye
is the function public
What does come up now that you've switched to an actual object
yup
Game object
transform
and
Got it now
It needed a capital letter
Thanks
what did ?
The name of the function
full sentences? is your !ide setup
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
no it doesnt lol
maybe because this time you dragged in the actual isntance thats on a gameobject
No it didnt work before.
the spelling has no relevance to if it shows up or not
The function comes up but it doesnt Do its job
show the code
and what do you expect it to do vs whats happening now?
The naming violation is merely a suggestion, and won't prevent your code from compiling
Its a restart game button
Its only purpose is to just reset the scene to its original
put Debug.Log inside see if the function runs at all
probably isn't (or scene would reset ofc)
Its not
I couldnt tell you, Its my first ever game
well start lol
you're the one at the computer with the project open
I can only give you pointers , I'm not telepath
Yup
first step is to check your hirerchy for an Event System object
if you have one, run the game.
check the event system inspector, it has a bar you can uncollapse at the bottom, it will tell you exactly what you're clicking etc.
That might be it, one second
No i dont think so
you have to check this
#π»βcode-beginner message
this isn't a guessing game lol you have to debug it
System event inspector can be found where?
do you have an Event System gameobject in your hierarchy
yes
do you know what the inspector is?
yes
so what do you think the answer to
System event inspector can be found where?
is
no Event System tells the UI what ur clicking
or otherway around, either way they work together
Show a screenshot of your full Unity window, with the hierarchy visible, and with your button selected
I fixed it
Yea that was it thanks
gamers i have a question, i made a method that determinates the players position in a race based on finished laps and checkpoints. It seems to work, but sometimes it like spazzes out.
Checkpoint and lap progress gets tracked well
public int GetPlayersPosition()
{
var playerPosition = 1;
foreach (var aiPlayer in aiPlayers)
{
if (lapProgress[aiPlayer] > lapProgress[humanPlayer])
{
playerPosition += 1;
}
else if (lapProgress[aiPlayer] == lapProgress[humanPlayer])
{
if (checkpointProgress[aiPlayer] > checkpointProgress[humanPlayer])
{
playerPosition += 1;
}
else if (checkpointProgress[aiPlayer] == checkpointProgress[humanPlayer])
{
var nextCheckpointId = (checkpointProgress[humanPlayer] + 1) % checkpoints.Length;
var nextCheckpoint = checkpoints[nextCheckpointId];
var aiDistance = Vector3.SqrMagnitude(aiPlayer.transform.position - nextCheckpoint.transform.position);
var playerDistance = Vector3.SqrMagnitude(humanPlayer.transform.position - nextCheckpoint.transform.position);
if (aiDistance < playerDistance)
{
playerPosition += 1;
}
}
}
}
return playerPosition;
}
My only guess is that I should add more checkpoints so it becomes more precise
or maybe there is some flaw in my logic that im not seeing
so you're just getting the raw distance from their current position to the next checkpoint. in some places they could be further back along the track but technically closer to the checkpoint, if you look at the bottom left two checkpoints around that curve and the middle two at the bottom that will be most evident there.
What I would do is instead use something like unity's Splines package, create a spline that follows the track then sample the position along that spline, then you'd also just sample the check point positions along the spline and you can get the distance from those positions along the spline
thats actually smart
so basically get the position on the spline thats closest to the player, then get the distance from that position to the next checkpoint
the distance from that position to the checkpoints position along the spline. the key here is calculating the distance along the spline. if you aren't doing that, then you're still just getting the raw linear distance from one point to the other
I have put this code on a trigger that the player will walk through. I want it to give a debug message every time he has collided an even number of times. (entering the room and exiting)
For whatever reason it only gives the debug message when the collisionCounter is 2. Not on 4,6,8 and so on collisions
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LagerDoorTrigger : MonoBehaviour
{
[SerializeField]
private GameObject playerObject;
private int collisionCounter = 0;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject == playerObject)
{
collisionCounter++;
if (collisionCounter % 2 == 0)
{
Debug.Log("Outside");
}
}
Debug.Log(collisionCounter);
}
}
Hey, i tried to add System.text.json pacakge to my unityproject via editing the csproj file and running dotnet restore in terminal but this didn't work so i tried to revert it but this fucked up my entire visual studio project it says that System.Void System.Object ... is'nt defined even tough it shows these errors in vs my unity project does run
so delete the .sln and .csproj files
do you perhaps have your console set to Collapse? because if so, then identical logs will be "collapsed" and show as one log with a counter at the far end. which would really be the only reason that would appear to not print that Outside log when the collisionCounter is an even number other than 2
Hmm how would I check that?
Oh I see now
Yup works, thanks didn't expect it to be that simple 
i deleted them but the issue is still the same
did you close and open VS and Unity?
yes
odd, screenshot the errors and post the .csproj file to a paste site
i think ill just create a new project and copy the files but thanks anyway
i made a 2D snowboard game and I'm using left/right arrow keys to rotate the player. I'm using torque to rotate it. The problem is i built the project and when i start the game the player rotates really slow. But it works well in studio
show code
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
[SerializeField] float torqueAmount = 1f;
[SerializeField] float boostSpeed = 25f;
[SerializeField] float baseSpeed = 17.5f;
bool canMove = true;
Rigidbody2D rb2d;
SurfaceEffector2D surfaceEffector2D;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
surfaceEffector2D = FindObjectOfType<SurfaceEffector2D>();
}
// Update is called once per frame
void Update()
{
if (canMove == true)
{
RotatePlayer();
RespondToBoost();
}
}
public void DisableControllers()
{
canMove = false;
}
void RespondToBoost()
{
if (Input.GetKey(KeyCode.UpArrow))
{
surfaceEffector2D.speed = boostSpeed;
}
else
{
surfaceEffector2D.speed = baseSpeed;
}
}
void RotatePlayer()
{
if (Input.GetKey(KeyCode.LeftArrow))
{
rb2d.AddTorque(torqueAmount);
}
else if (Input.GetKey(KeyCode.RightArrow))
{
rb2d.AddTorque(-torqueAmount);
}
}
}
this is my controller script
I think you need to put the physics code in FixedUpdate
use a bin site for large blocks of !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.
and yes, apply physics in FixedUpdate rather than Update
ye, this'll cause it to be frame independant so it won't change how fast it's turning based on the framerate
ok thank you! lemme try
Hi, I sent this code yesterday that makes no sense to me, I would really appreciate somebody explaining what's going on.
These 2 should behave exactly the same(from my understanding):
public static Camera Camera => Instance._camera ?? (Instance._camera = Camera.main);
public static Camera Camera => Instance._camera == null ? Instance._camera = Camera.main : Instance._camera;
Yet, 1st one results in a ton of null ref errors while the second one works flawlessly.
They are in the same script, same position(literally one above the other) and I even use the same piece of code for my time manager which just works:
public static TimeManager TimeManager =>
Instance._timeManager ?? (Instance._timeManager = GO.GetOrAddComponent<TimeManager>());
According to ai and a person on this server(asked the same thing yesterday), it should work the same, yet it doesn't.
Thanks in advance!
did you read the error message?
how do i publish new update to my game?
yesterday i built the project
you build it again
π
Never use the ? or ?? operators with Unity objects
I did, the _camera is not set, how come tho, if it's null, it should assign Camera.main to it in both cases, am I missing something here?
you have been warned
good to know, I never ran into issues before but I'll test properly from now on, thanks.
Is there a reason why it works with the TimeManager(just a regular mb script) and not with Camera?
Like does camera have something specific going on in the background?
I am just curious.
I totally spaced that - but Unity overloads the equality operator, so Objects can be == null to represent an uninitialized or destroyed Object even though they're not actually the value null. ?? doesn't use the equality operation, so
public static Camera Camera => Instance._camera ?? (Instance._camera = Camera.main);
always evaluates to Instance._camera even when it's not been assigned
Interesting, how come TimeManager works then?
Is Camera inheriting from something other than MonoBehaviour?
You can look at the Unity docs, but Camera derives from Behaviour, not MonoBehaviour . . .
it worked bro thanks!
I see, I guess that would probably explain it, thanks a lot!
Though, ultimately, it derives from Object . . .
I couldn't for the life of me figure this out but I found a workaround, thank you!!
lol, ultimately it derives from object, just like everything else
what was not clear about the information presented on that page?
its not that it wasnt clear i just didnt understand it all that well, when i typed in instance.Initialise(_target); into my code i got an error message
ah yes "an error message"
but i'm gonna go ahead and assume you didn't bother creating an Initialise method that takes a parameter on the type you were attempting to initialize?
'GameObject' does not contain a definition for 'Initialise' and no accessible extension method 'Initialise' accepting a first argument of type 'GameObject' could be found
right so you were actually using the incorrect type
as you can probably tell, im new to unity so everything i take in that isnt "write this variable here" goes over my head
there is almost never a need to make a variable a GameObject type. use the type of component you actually care about
then start with the beginner courses pinned in this channel so you can learn wtf you are doing
rawdogging it π
Exactly, haha . . . π
guys when i start my game my sound effects and particle systems starts on their own why?
Do you have PlayOnAwake checked?
Play On Awake ?
lemme check
don't expect help if you refuse to bother learning the basics
ok man chill, i'd feel like i learn less if i sat at my screen reading for ages and not just going in and learning practically
thank you for helping though
yes they were!
the thing is though, is that you aren't learning practically. you are just blundering along relying on others to tell you what to do
π€« this is the first time i've asked for help with programming in years
maybe you're right though but i wouldnt enjoy reading tutorials the whole time
Help, how can i save and load a gameobject rotation?
this is my save:
rotation[0] = myPlayer.transform.rotation.x;
rotation[1] = myPlayer.transform.rotation.y;
rotation[2] = myPlayer.transform.rotation.z;```
This is how i try to load:
```Vector3 myRotation;
myRotation.x = data.rotation[0];
myRotation.y = data.rotation[1];
myRotation.z = data.rotation[2];
thePlayer.transform.rotation = Quaternion.Euler(myRotation);```
transform.rotation is a quaternion, not euler angles
https://unity.huh.how/quaternions/members
but also what are you even using to save this data? it may be possible to just store the quaternion directly
you forgot about the w and then you treated the xyz as if they were euler angles, which they're not.
but if i don't do quaternion i get error
"do quaternion" lol
thePlayer.transform.rotation = myRotation; Cannot implicitly convert type 'UnityEngine.Vector3' to 'UnityEngine.Quaternion'
again, transform.rotation is a quaternion
because myRotation is a Vector3
why would you try to put a Vector3 into a Quaternion field
that part wasn't even the issue. the issue was the first part where you store the data
well... both are the issue
because im dumb i guess
not if they'd store the eulerAngles in their array
sure, or if they restored it as a quaternion (and stored it as one)
they jsut have to pick one
well we don't even know if they can store the quaternion because they elected to ignore the question about how they are actually saving the data π€·ββοΈ
or i suppose they could probably make the array larger. but honestly an array for this seems absolutely pointless either way
well presumably if that mechanism can handle a float[3] it can handle a float[4]
but yeah
In a 2D top-down view game is it better to use a OverlapBox than a Circle?
When attacking
use whichever shape makes the most sense for whatever you are doing. there is no "better"
There is no "better"
It depends on the shape you want
And how can I make my character, in that same view, face the way I am moving
in terms of the transform
I have a movement vector, how can I make the transfor "look" that way
assign either the transform.up or transform.right to the direction of movement (depending on what direction it faces with no rotation applied)
Whichever direction is the default facing direction, assign that to the movement direction . . .
InteractableObject and Interact To Progress both inherit from Monobehaviour, why can I only disable InteractableObject?
it doesn't have any methods that would be affected by being disabled so it just doesn't render the checkbox for it (this was changed in unity 6 i believe)
even if it did render the checkbox, there's nothing that would be affected by its enabled state
why is my collider not lined up with my actual circle gameobject
i keep having to resort to using offset
to get it lined up
is there any way to fix this simply?
where is the code question
my bad didnt realize i was in the scripting section
which channel would this best be for?
unity talk is fine?
christ are you ever going to stop with the constant barrage of messages because you don't know how to finish a thought before sending a message?
ohhhh lol you're that person, funny
I have an error:
Assertion failed on expression: 'SUCCEEDED(hr)'
does anyone know what this could mean?
"that person" you mean the person who pointed out the literal server rules about spamming and not using full sentences?
go read up on #πβcode-of-conduct again then look at the pivot point of your sprite to fix your issue
Ah I see thanks! As long as I implement start or update itll work right?
Very interesting implementation
sure, but like is there any reason you need to disable that specific component?
There's really not enough information there to go off - can you share the full error and stack trace?
Quest system: Some components get enabled or disabled depending on which part of the quest the player is in. By default this is off
that's all, I have this message (in fact 4 of these exact same messages) when I open older projects or create new ones.
you can still set its enabled property in code even if the checkbox isn't there, but that still won't make anything at all happen if there's nothing that will actually be affected by being disabled
so what is the point of disabling a component that won't be affected by that in any way?
oh wait I was disabling the wrong component π
No filename or anything? Even when you select one of the messages?
Yep, but this error doesn't affect the game at all... but it still is kinda annoying
which Unity version?
2021.3.38f1
My workflow would be made much more convenient if I could operate with two prefabs open at the same time, but even when starting a new Game tab opening a prefab controls all Game tabs
Any way I can work on multiple prefabs at the same time?
LTS
You can have two inspectors open if that helps
trying to get a weapon pickup system working, and my player simply isn't colliding with the weapon pickup on the floor.
the player has a rigid body, both the player and the weapon pickup have colliders - the weapon pickup collider has 'is trigger' on - and i've checked that the layers they are both on can collide with eachother in the physics matrix
i have also tried using OnTriggerEnter2D instead of OnCollisionEnter2D and neither work for me, currently all i need is for the 'canPickUp' bool to be checked when i move into the weapon pickup collider
KeyDown is one frame event, and so is oncollisionenter . You would need to be non-human to hit that correctly
i would also strongly recommend against using Collison/Trigger messages for interaction systems. use a physics query like an OverlapCircle instead and you can have all of the relevant detection code in Update on a single object so you not only don't miss input (like what is clearly happening here) but also so you don't have a hundred different objects always checking for something that can be checked from one central location
currently not too worried about getkeydown working, but thanks for this info anyway, using ontriggerenter would be better then
alright thank you ill have a look into this
I don't know if i read it right but if you gonna use ontriggerenter both objects needs to have a trigger hitbox (What i know) I was wrong
incorrect, at least one must have isTrigger on. but both can have it enabled
Oh sorry my bad, Also a noobie
the page i linked goes over that kind of information
!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.
Hey, I'm currently trying to turn on one light after the other on a path.
For now I can turn them on, but I'm having a mistake somewhere where the lights aren't turning on one after the other, but all at once.
https://gdl.space/amudakasos.cs The script is attached to a functioning trigger object
that loop completes in a single frame. you'll want to extract the loop into a coroutine and yield for your desired time each iteration so they enable one at a time
On a side note, this condition seems a little peculiar as well:
if (Time.time - timeIntervalCandles >= 0)
it checks if the game has been running for timeIntervalCandles seconds
it can also be done in Update with a simple timer variable.
i have question, i dont have idea why playerdatainstance dissapears after i start game> any clue why it dissapears from its field after i start game
This is the beginner coding channel, for non-coding questions try #π»βunity-talk
oh sorry then, (so im not beginner anymore?
)
Oh
Thank you
i imagine this is probably related to your code which you would have to show
if it isn't related to the code though, then definitely not appropriate for this channel as this is a code channel
It was resolved
#π»βunity-talk message
Guys i have a raycast that stop working when i add a collider to the object, how can i fix it?
The collider blocks what you expect to hit?
Show code
ya ik how can i fix it
ill send the code
Put some debug logs in. Which condition fails? I am guessing the collider.transform is not the player_transform
yup
its hitting its own collider
Ok. Remove that layer from the layermask
the objects layer?
The one you do not want to hit
ok ill try it
Hi guys! I'm making a VR game and I'm using the XR interaction Toolkit. I was wondering how I could make a grenade? I've tried but I can't get it to work
You should try and narrow that down to a more specific question... there are a lot of different aspects to implementing a grenade
not sure how vr hand controls work.. but u need to pass on velocity to the grenade
(sphere w/ rb)
well, I guess getting it to detect when it should go off, like it only going off when the player presses the trigger and after that the next thing that isn't the hands that it collides with it will explode and destroy itself, that's my basic idea but I don't know how to do that. I can try to narrow it down even more
Unity's XR toolkit already does that for you
If you mean "go off" as in explode, you could just use a normal OnCollisionEnter() event to detect impact and explode. The hands could be omitted from triggering the collision via layers.
For the actual explosion, you might have the grenade instantiate a prefab encapsulating the relevant effects - particles, audio, and maybe using a physics query to detect rigidbodies nearby and apply an AddExplosionForce()
(one of many possibilities π)
ya, shouldnt be interacting with hands once released
when instantiating a prefab it loses some scripts and gameobjects, i know this is intended but i need to know how to add those back into the prefab upon instantiation in the script, heres the code so far, any help is appreciated ty
why cant I make an abstract method static / is there something else with similar functionality
ive looked around on the internet for a while everything im seeing i cant figure out how to implement properly
wdym it loses scripts
instantiate returns an obj..
okay so when i add everything to it in the hierarchy then make it a prefab it loses some things, heres a screen shot
use that to then grab components /and or set up other values once instantiated
Statics aren't ever inherited, so they don't make sense as an abstract
is there a way to say I want all child classes to have some kind of static method
Imagine you have an abstract static method. Then you use the base abstract class name to call it. Which implementation would be called?
Have a non-abstract static method call an abstract non-static method
you could always create a singleton
couldnt u just do what it normally does
highest possible reference
i understand this functionality but am unsure how to implement it to get the components properly
What reference? Static methods are not bound to any reference. They're called from the class-level, not instance-level
smart
On a bit of a tangent, I think you can define an interface with static members, but then it might make a mess of inheritance... I'm assuming a parent and child class cannot both implement the same interface, because that would make an inheritance graph rather than a tree/chain? π€ (brain fart)
Edit: shower thought. Pay me no heed - I'll play π
Edit edit_v2_final_final.doc: ewww
maybe highestpossible class in hierarchy
well not highest but the same way they do it for casting
Which one? There can be multiple deriving classes
You call a static method on class-level, not instance-level
MyClassName.StaticMethod
If it's abstract, you can call it from the base class which declares it
From there it makes no sense which implementing class to choose
how would i add the player movement script into the "Player Move Script" slot on the prefab, currently trying to use getcomponent but dont really know how i would add it to the prefab
get component just grabs the script using <Type> soo it'd be whatever your player script was.cs
Using Unity.XR, how do I find my controllers using roles?
many different ways to do it.
PrefabScript prefabScript = instantiatedPrefab.GetComponent<PrefabScript>();```
now all its public variables are methods are accessible like prefabScript.ReferenceA = ... ;
or prefabScript.DoFunctionA();
would cancelling inputs be a good way to limit speed on a rigidbody? (just WASD)
IGNORING inputs that put the velocity over a value may be fine, and is not uncommon
yes this is what i meant sorry π
ya, weird phrasing lol. ignoring inputs over a limit is just basic clamping
my code in my main script got all messed up because unity autosaved and i didnt have a backup when it did
So if moving "left" at the max speed, just don't add speed when pressing A. But if you press D, then decrease that velocity
so now i have to redo everything
unity autosaves now? π
Uhhh... are you using version control?
no sadly
No. Must be an external package
Stop everything right now and get it
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
there we go
It is dead easy. There is no reason not to
use a graphical program.. and watch / read a tutorial or 2
its pretty easy within the backup, change, pull/push, aspect of it all
version control seems very useful and would have probably saved me a couple times π
i will get on it
one of my harddrives just gave-out last month..
it was an awful ordeal. but knowing atleast some of my projects were on VC made it not as bad
ruining a scene is 1 thing.. losing a project or two.. pretty much ties ur hands to using version control, if ur half-sane
How do I fix this? I can't find what varible the XR controllers are
so I can't make a varible for it
this helps thank you, so now i have access to the player movement script inside the script i am instantiating the prefab, but then how do i actually plug the player movement script into the prefab (am i missing something?)
well for starters, according to the docs page, this method is obsolete so you wouldn't be using it anyway π€
any idea why it's not recognising this as a variable for player?
im using 2.4.3, not 3
it isn't that it isn't being recognized. it's that when you go to access it, it is not assigned. either something is unassigning it in code, you have more than one of these components in the scene where one isn't assigned, or the object that has been assigned is being destroyed
i'm assuming you are referring to the XR Interaction Toolkit which that method is not a part of
oh, well im not sure what to use then
well what are you actually trying to do with that line then?
trying to get access to my controllers so I can check if the trigger is pressed
also if grip is too
and have you looked at the documentation to see how you might do that? or have you gone and looked at ancient tutorials that use methods that have been obsolete for years?
if the playermovement is on the prefab already once you load it, it will be there. make sure all your values are correct on the script
I looked at the docs and saw the role feature so I tried using that
what doc did you look at
aye be honest, i am looking at a brackeys youtube video and he's using github is this good to use? or would you recommend something else.
github is pretty much the industry standard. use it
thank you π
I miss omnisharp checking my whole project for syntax error when I press F8 :<
even if that method weren't obsolete, the example you copied from shows you the declaration and initialization of the gameControllers variable
what code intelligence server does unity call the one they uses now?
but when using the xr interaction toolkit, shouldn't you just be using the input system for input? like that's literally a requirement for that package
what are you talking about? omnisharp is still what is used for vs code's intellisense
really?
how do i figure it out
This means that your ide is not configured correctly. Check the config guides. !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
why would you think it isn't?
the slot for player movement is there but the actual script isnt inside it
thought it was c# devkit shit
well start by looking for other copies of that component. you can use t:CameraController in the hierarchy search bar to find all instances of that type
the C# DevKit just installs relevant c# extensions. omnisharp is part of the C# extension and likely always will be
it is configured, but it wont find any errors that is not in the files tab
show me a picture of what you mean
i started a thread so it doesnt get messy here
That declaration didn't work tho
it doesn't even matter if it did because that method is still obsolete
oh its been replaced with Characteristics
And I think that's the normal behaviour. You don't want intellisense scanning your whole project all the time. Though VS might be doing a better job with that. Anyways, you should be looking at the unity console first and foremost.
hello i'm completely new to unity and c# and i have an audio source component attached to a gameobject and i just want to trigger the sound through code. how can i target the audio source and play the sound?
it automatically resolved itself once i fiddled with visual studios settings
thank you tho β€οΈ
those are entirely unrelated things
this might have an issue not relating to the script, but when i build the project the player can't move, they player can fall but there is no movement, although its fine when playing in the editor, this is a first person 3D project
https://gdl.space/kopilikixo.cpp
fiddling with VS settings would not solve a NRE
you probably got rid of the extra script with unassigned reference
Hi friends.. I am getting an error on line 39 here.. it says: You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
The other class looks like this as you can see in the SS. why that doesnt work?
you are doing new AreaOfAttack
AreaOfAttack is a MonoBehaviour
pretty clear error if you ask me lol
because you are doing new, you cant do that on a MonoBheaviour
you should not new a MB
so you didnt do that always, because its impossible
Was that classname a MonoBehaviour?
It is perfectly fine when it is NOT
But yeah, you could NEVER have done new on an MB
When you think about it, it doesn't even make sense to
it was either empty, or a ScriptableObject or something, like the error suggest you can fix it like that
You CAN new a gameobject. I'm assuming it was maybe that?
no idea tbh, but it says you can in the error π€·ββοΈ
I mean, an MB is a component. How can a MB exist outside of a gameobject?
Understood. Thank you guys.
oh true maybe Im mistaken ? its been a while thought we use the method for it π
Already fixed here. Thank you all
I have so much difficulty with null reference.. the day that I learn how to master this.. I think I will speed up my games progress 1000%. Just a comment. π
null references will be the least of your problems in the future lol
Anyone knows how can I serialize a script inside a component? I would like to inside the inspector be able to chose the 3 public atributes of health. Is it possible to do this?
does Health have a reason to inherit from MonoBehaviour? if no, then don't make it a MB. if yes, then the only way you'd be able to do that is to write a custom inspector that will then write to the serialized fields stored on the reference assigned to your PlayerManager
hello all, im not sure how to phrase my question correctly so please clarify if there is confusion: when i exit a scene and load up a main menu scene and then load up the first scene again, nothing works, why is that and how can i fix it
here is the main menu loading line
cs UnityEngine.SceneManagement.SceneManager.LoadScene("mainmenu");
does anyone have a tutorial about row and collums, im trying to make a summoning script that spawns objects behind u in rows
are you perhaps exiting from a pause menu? because most of the time issues like this are caused by setting timescale to 0 in the pause menu but then not setting it back to 1 when returning to the main menu so it ends up staying 0 when loading back to the game scene.
if that isn't it, then you need to provide more information
Is it better to not inherit from MonoBehaviour? does it consume resources? Also, is it possible to write a custom inspector, how could I do so? I think I will have to do it for other clases
this is like the third time you've helped me lol how do i give you karma
it's not "better", it just entirely depends on what your needs for that object are
hahaha Well if I manage to never get this one again I will be already super happy.. I lose a lot of time around it still.. π but I understand what you mean hahaha. !!
is it possible
Well... they did suggest it
It is a big topic, but there are many guides online
I see, for the Health script monobehaviour isnt needed, but my other scripts will
If you want it to be a direct component, then you need it to be a MonoBehaviour. If it is just data, it does not have to be
What do I have to search for the tutorials?
"Unity custom inspector"
Okay thanks
there is also documentation about extending the editor pinned in #βοΈβeditor-extensions
Question about building a .exe
Does it always need the folders? It always makes a BurstDebug, Data, MonoBleedingEdge, and a dll.
Do i need to upload all of these to share my game? Unreal does a similar thing idk if im missing a setting.
the only folder you don't need and should always delete is the one that literally has "DoNotShip" in its name. the others are absolutely necessary
are you guys talking about version control? i really need to look into that
no, but you should be using some sort of version control. i personally recommend and use git, but unity's version control package is decent from what i've heard
Does that back up your entire asset folder or just code
you commit what you want to your repository
So git can store all kinds of files? Thatβs cool
Hi guys.. I have a situation here. I want the player to attack enemies if he enter this area. If I put on the variable to attack only in 1 unity so float areaOfAttack = 1; It will attack correctly in 1 square unity. But the scale of my circle is 2.1 I want it to be always the circle area. And I do not want to use collision to check this.. any fix for that other than using collision 2d?
yes, just keep in mind that for files larger than 100mb you need to use LFS which has a storage cap for the free tier (though tbf UVC also has a storage limit for free tier)
Is the purpose of git to create a copy essentially in case unity files get corrupted? Iβm just not sure what the main concern is
no, it's to track changes to your files so you can revert those changes, work with others, and as a bonus hosting the repo on a remote repository serves as a backup for the files
Ok, thanks Iβll go do that
Instead of areaOfAttack why dont you just use the object's scale?
omg, hahaha i didnt think about that. You are a genius.. Thank you !! hahahaha
HI guys when I try to use the Console.Writeline nothing appears on console.. any ideas?
Why not Debug.Log?
Amazing, that worked. Thank you.
Anything starting with Console. is not for use in Unity. It is for console apps
It technically can work, just not as smoothly or as easily as the Unity API (like Debug)
can I pass a bool by reference?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref
Could just returning a bool work though? it's generally better
What in particular are you trying to do with it? Maybe you can avoid having to pass the bool and instead pass what owns it.
i dont even know if this is going to work but im trying to call a coroutine from a different script and have that coroutine pause and resume only when the method in which it was called is run again
Pass a reference of the object that owns the bool
as in the script?
Coroutines won't take ref parameters.
Script is a word for a file. So no.
Pass the class, which is an object
can't pass ref parameters to the coroutine so that will be the best option. or pass a func that returns the state of that bool and use WaitUntil
i thought you cant do that with monobehavior?
Do what?
Pass a reference to it? Of course you can
public IEnumerator MyCoroutine(MyScript myScript)
{
while(myScript.myBool)
{
//do stuff
yield return null;
}
}```
I cant believe i didnt know you could pass Monobehaviors as objects
a whole world has oppened up to me
MBs ARE objects, to be clear
this whole time I had been using GetComponent<>
so I thought you could only do it from other monobehaviors
UnityEngine.Object > Component > Behaviour > MonoBehaviour
How can I get VR controller input using Unity XR? I've been trying to figure it out but I just can't
May be best to ask in #π₯½βvirtual-reality
oh yeah thanks
It's a type (class) just like anything else. Why not?
I just figured since you couldnt instantiate them traditionally you couldnt do other things
with programming, never assume . . .
wheree is the site to paste 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
i found it, thank you
no, i have my ide
no, i found it first . . . π
It's not about having it, that was for configuring it. But yeah, they meant !.code (split to break the call)
oh shit, you right. it was !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.
https://paste.ofcode.org/jFRC6ZJkXqdRYpCkBgHVFH in the SummonBarbarian method im trying to make it so the cloned gameobject spawns behind my player in rows but its just spawning on top of me
oh, okay
thank you guys!
i knew that . . . π«
Do you know how to use the debugger? I would put a breakpoint in and check values at runtime
did you debug what those values are? unless you changed them in inspector
0 * anything = 0
transform.position - (CurrentRow * RowDistance * transform.forward) - (CurrentCollum * RowDistance * transform.right)
=> transform.position - 0 vector - 0 vector
whats that?
ill try changing the value to two or something
well dont just randomly change stuff
Something you can google for a guide.
But you can just do Debug.Log for now
this should be used for something, did you use AI to make this code?
oh alright, ill do that
yeah i used it for some help
I recommend against that
well you shouldnt, as you have no idea what this code is doing
i figured out what most of it is
and yet here we are
maybe we can get chatgpt to join the discord and when it sees code it wrote it can chime in, hey I wrote that code, let me help you fix it
it didntntntn helppp!!!
my computer is so slow im sobbing
is Debug.Log(SpawnPositon); enough for trying to debug it?
Or it'd say, "you didn't copy my code correctly"
i tried understanding it before i wrote it
my code is super buggy, i think im just gonna rewrite it without ai thank you guys
Not the best
But what did the log say?
i did also point out one likely problem above. you should debug what the difference is between the transform.position and spawnposition is, since your issue is that they're spawning ontop. Then you debug further with possibly the results of CurrentRow * RowDistance * transform.forward or CurrentCollum * RowDistance * transform.right
i pressed space four times and i got (-5.07, 1.17, -0.54) four times, it stopped spawning at me cause the values i changed in the code didnt change in the inspector for some reason so i just changed it there
alright, thank you ill do that
after CurrentColumn goes back to zero it goes infront of the first clone spawned
i got it to work, thank you guys
I just wasted like 2 hours because I was trying to hit a box collider (not 2D) with a 2D raycast
fml
no medicine for stupidity
Debug.Drawline my raycasts if at all in question
That would not help in this issue. But yes, that is an extremely useful tool
hi, does anyone know how to make unity "refresh" my compiler errors after i fixed them in vs code (so that i can start play mode)?
for example i acidentally write nonexistent variable "radius" instead of just putting a number , and it caused a compiler error, but after i fixed it unity hasnt caught on that i fixed it already, and i have to restart the engine every time it happens
Did you save the script?
yeah i saved it in vscode
Unity should be watching those files and recompiling/reloading the domain automatically π
Did you change the Unity configuration to not auto compile?
im following a tutorial to make subway surfers and i came across a line of code called Math.Lerp, i know what it does, so u give a minimum value and a maximum value and then a starting value to the third and he is gonna randomly choose a number between the min and max right? so i understand that but i dont know what the tutorial is doing, i'll send u a photo of the line of code
the minimum is x but x doesnt have any value in this whole block of code
He just put a variable on top like this, Private float x; is this default on 0?
and he is using the lerp to determine the animation time to dodge i think but i wonder why he is using lerp? because it'll chose a random value between the min and max so wont this effect the animation because its a random number every time?
yes this will default to 0
also most of this tutorial code looks horrible
Hmmm, but why does he uses lerp? so i know its for the animation but isnt the random number gonna affect the animation or something?
i dont understand why u should use lerp for animating
not sure what random number you're talking about
the only part that controls the animation is the .Play call, nothing else affects your animation itself
Well, the math.lerp is chosing a random number between the x and the NewXPos right? and what is the Time.deltatime*Speeddodge then? thats the random number right? or?
why random? where do you get that from?
lerp is a linear interpolation between A and B, at value T where t is between 0,1
oh its a loop?
well, the code is shit but they're also not using a value over 1
basically, because he doesn't know what he is doing
Well yeah i understand that but i just wanna know why he does uses it and how it works
he probably learned his Unity code from Brackeys tutorials which are full of this kind of shit
it works tho so? i just want to understand what it does in this case? so he choses a min and max value, then he does the time.deltatime* speeddodge?
is this to determine his position in wich lane he is? because subway surfers has 3 lanes i guess?
ok, think of it like this
x is min, newPos is max and time.deltatime* speeddodge will always produce roughly the same value between 0 and 1
So...
the lerp return the factor of t between min and max so a value between x and newPos. but...
because it is updating x with this value, the value returned will gradually move towards newPos.
so Lerp is normally
current = min,max,t where t changes
what he is doing is
current = current, max, t where current is changing and t is static
ok yeah, thanks for that i now understand how it works but i still cant fully understand why he uses it? its somemthing used for moving the character i think? but why would he use that lol?
whats the thought behind that
because x will always be slightly different no? bcs the time.deltatime will constantly be slightly different
basically to make a framerate indepentant value of x to modify the position by
no, it will be slightly different because he feeds x back into the calculation
and not the time.deltatime? because thats not always the same right?
why would he modify the position by the framerate? my brain isnt braining
as near as damnit, that's just to adjust for frame rate changes to make the progression look smoother
ah so its almost no difference so u wont notice it?
you adjust by framerate becauuse you do not want your movement to be fast on fast computers and slow on slow computers, you want it the same on both
aaah ok i know why he does it, so he moves the character the at the same speed always on every pc/phone etc... and the x value is always different based on how fast your computer is? but one thing i still not understand is, u say the value of lerp is always between 0,1 but time.deltatime * dodgespeed is always higher than 1 right? dodgespeed in this case is 10f
or is time.deltatime a really low number?
no, it is always less than 1
think about deltatime on a pc running at 200FPS it is 1 / 200. On a phone running at 30FPS it is 1 / 30
your game is shit and no one will even play it
Lmao ok ok
thank u very much for the help, i appreciate it alot, i atleast know what it does and why he uses it
As bawsi said, this is horrible code so don't take it as 'this is the way it should be done'
Also there is a max delta time to specifically stop cases like this from massively affecting your game. I think it's like 0.3f by default
okay, got it!
oohh ok ok, thanks for letting me know
one other thing with Lerp, if t IS > 1, it will just return the max value
https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html
if u look at this link at the code block, is this used to move an object from left to right and back from right to left?
Guys how can i move the trident forward in its direction and keep in mind its a child of the circle?
yes, the comments indicate this but also you should always
. Copy the code and see it in your own project, you can debug values and see it in real time
yes
hello
i need to make a "pause game" system for my game, looking for implementation
I'm trying to make all parts of the game to be dependant on internal "pause" flag, rather than using Time.timeScale.
Is it a good implementation, or is there another way? Because i feel like Time.timeScale may not be the best solution, because it can influence more than just gameplay i.e. menus and such
People how can I have this code?
Follow the instructions from the beginning of the page. Looks like a tutorial from the title.
itll be really annoying trying to do this all from one "pause flag". First thing that comes to mind is rigidbodies and coroutines. You would have to include some additional check in a coroutine and have a separate script which stops rigidbodies.
What "menus and such" are being affected? This is extremely vague
At the bare minimum you would have to recreate your own values for timescale, deltaTime, etc, just to have a simple working version. And even then you need to handle rigidbodies somehow
like animation of a menu sliding in/out of screen
i understand that it can be bothersome, i just don't know how bad of a practice this is
oh
Do I have to initialize all variable default values like I would in C++ to avoid UB?
so using timeScale for a pause is, like, one of the best solutions?
ever since I had a time where not typing x = 0 got me a UB in C++ I became terrified
No. You'll get compiler errors if you try to use an uninitialized variable, and runtime errors if you dereference a null reference
ayeay
I have a problem, hit count is zero when the game is paused, time scale is set to zero but when the cursor position is on the gameobject and I resume the game and afterwards pause it again, it would be OK!
var ray = _cameraCollection.Main.ScreenPointToRay(_inputController.CursorPosition);
var hitCount = Physics2D.GetRayIntersectionNonAlloc(ray, _results, distance, layerMask);
It is in update routine.
I mean the problem is when the game is paused and I hover on a gameobject. It cannot return it but if I resume and pause, it is OK
Value types you dont need to, unless it's a local variable. Reference types will be null
One of the easiest, and doesnt require any changes elsewhere yes.
good enough for me i guess
big thanks 
as opposed to C++ where you need to initialize absolutely everything, right? If memory serves me correctly
It's been too long since I've done c++, I dont remember tbh
I shall google then
https://gdl.space/ujazelizem.cs some lifehack if anyone needs :3
put in editor folder, rightclick a script you wrote, and select autograb components, automatically fills any field for you :3 (if it thing is in the gameobject and/or child )
You mean component fields?
How come I don't need to do the whole = new List<>... thing? I thought ref types were initialized null
Seems like a good way to accidentally fuck up a reference that was to a prefab or scene object
The new word is needed, the type is already known
Ohhh that's what it means
Yeah, it wouldn't be nice for external dependencies (component references that would be from other objects)
so if I declare it w/o new'ing I'll get null ref right
yes, if it is not a serialized varialbe
you'ld have to manual that then, or ||use find
||
Why does that make the difference? And does that have anyhtingt o do with [serializeField]
I never use find ||- unless I'm writing code for others or am in need of mad automation||
Also was wondering if there was a container in C# supporting both lifo and fifo
whatabout find via Tag

Basically it wont be null if unity serializes it, with public or SerializeField. Itll be initialized still
it makes a different because for serialized variables Unity does the new for you and fill the data which have been serialized
all find bad, with bytypes being worst
With proper referencing, you don't really ever need to use Find unless it's something unexpected
If you want to improve it, maybe make some editor script or an attribute which let's you do this for certain fields rather than this reflection stuff
Gotcha. So i'm assuming things like data containers are default serialized
no, dont assume, check the docs
Will do
Why is this not working??
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class ButtonActions : MonoBehaviour
{
[SerializeField] private UIDocument uiDocument;
void EnterFactory ()
{
Debug.Log("Entering factory");
VisualTreeAsset newAsset = Load<VisualTreeAsset>("UI/UXML Docs/GameHUD");
if (newAsset != null)
{
uiDocument.visualTreeAsset = newAsset;
}
else
{
Debug.LogError("VisualTreeAsset not found at the specified path.");
}
}
void MoreFactoryInfo ()
{
Debug.Log("Opening more info screen");
}
void FactoryTutorial ()
{
Debug.Log("Starting tutorial");
}
}
Define not working
also !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.
the name Load does not exist in the current context
Si just wanna change the source asset in UI document by code to change the UI screen while playing...
your code will not even compile, fix that first
For some reason classes expanding upon DefaultElement can't access it's protected variables. ANy idea what the case is?
https://hatebin.com/dossoeybqg <- DefaultElement
https://hatebin.com/hrvzbjdycs <- RoomManager (Expands upon DefaultElement)
The declared variable is commented out
what do you mean
?.
Better like this?
void EnterFactory ()
{
Debug.Log("Entering factory");
VisualTreeAsset newAsset = Resources.Load<VisualTreeAsset>("UI/UXML Docs/GameHUD");
if (newAsset != null)
{
uiDocument.visualTreeAsset = newAsset;
}
else
{
Debug.LogError("VisualTreeAsset not found at the specified path.");
}
}
Sorry for the format... I'm just doing it on my mobile phone
Why are you coding on your phone?
Write it on your computer, then see if it compiles
No, no hehe, I dont have enough connection to open discord on my pc hehe, I already have opened unity there
Also provide more information about what you're not understanding @glossy turtle
#854851968446365696
then I cant help you because the next thing I need is a screenshot
I'll try to change my connection... Wait a moment
ok, then screenshot the location of GameHUD in your project view
here I am
tell us what you want the Load function to do
oh nvm thats solved
OK, so that is NOT in a folder under a Resources folder
So, I just need to create a 'resources' folder inside my assets and move there the uxml?
Resources.Load finds stuff in the Resources folder.
Calling Resources.LoadAll<Objective>("objectives") will go to Resources/objectives, find all objects that are objectives and return an array of it.
ok havent seen the previous code nevermind.
best best, go read the Resources.Load docs, which you shuold have done already
resources folder should start with R.
Thank you all, lemme take a look at docs and try it again π
I still getting this log
I'll try to update the path
show where you moved GameHUD to
void EnterFactory ()
{
Debug.Log("Entering factory");
VisualTreeAsset newAsset = Resources.Load<VisualTreeAsset>("Assets/Resources/GameHUD");
if (newAsset != null)
{
uiDocument.visualTreeAsset = newAsset;
}
else
{
Debug.LogError("VisualTreeAsset not found at the specified path.");
}
}```
you really did not read the Resources.Load docs did you
oh, my bad! is it like this? ```csharp
void EnterFactory ()
{
Debug.Log("Entering factory");
VisualTreeAsset newAsset = Resources.Load<VisualTreeAsset>("GameHUD");
if (newAsset != null)
{
uiDocument.visualTreeAsset = newAsset;
}
else
{
Debug.LogError("VisualTreeAsset not found at the specified path.");
}
}```
yes
then, how could i load the uxml from a different folder without using Resouces one?
you cannot other than using an asset bundel or addressable
but you can have multiple Resources folders and they can have sub folders
So you definetly recommend me using this method? or would you use as you said me addressable objects/asset bundels?
that depends on your use case, if the asset is included in the build then Resources.Load is your only option other than a direct reference
Thanks! and one last thing... would you recommend me to move the entire UI folder in resources one to keep it organized?
no, you only want stuff in Resources that you will load with Resources.Load
so then the best option would be moving the uxml docs folder into resources one, right?
Or you make a folder Assets/UI/UIXML DOcs/Resources and move the stuff you want rto load into that
Resources does not have to be directly under Assets
Ohhh, that's possible!
That's definetly my answer π
And to load it it would be the same code?
yes
And if I had two resources folder, how would unity know which one I'm refering to?
Magic, just dont use the same asset name in multiple Resources folders
It collects all the Resources folders in the project.
Spoilsport, I prefer Magic
Lovely, so, thanks for you help! I'll read more docs before asking it here π
Me too :>
wdym, I do it every day and, btw, you have not seen my beard, long and white
i wouldnt have expected santa to have unity expirience
i guess doing nothing for 364 days makes you acquire hobbies
hello, is it possible to bind button scaling to length of the text?
You can use a ContentSizeFitter
Thanks
IBeginDragHandler, IDragHandler and IEndDragHandler acts like IPointerDownHandler, IPointerMoveHandler and IPointerUpHandler. Is it normal behaviour? I thought it should get called when there is a drag going on
So begindrag already triggers on first click?
Oh no. It fires at first drag. After that when i stop drag, it does not fires IEndDragHandler. The IEndDragHandler gets fired when i just do pointer up...
Hmm weird, have never seen one fire and the other doesnt, usually they dont work at all when there is a problem π
Ik I asked this earlier but... kinda stuck. How can I access the Text Child of "CoinsAmount" button?
Finding and Accessing the ScoreCount child was easy because there was only one. But out of three buttons, I don't think I can easily reference the text inside the score
Does anything prevent you from referencing it via inspector?
Just make a public field with TMP_Text as type and drag your Text Element into it in the inspector
With this piece of code I'm creating three lines in a triangle from the player, but...
Doesn't matter where the player is, it always points into one place
So that's the best way?
I was doing that earlier but for every level, will that be "effective"?
For now I only have 6 levels though
If the Element you want to change is always present and does not change dynamically that is the easiest way yes
You can create a level template that has the important stuff already linked and create copies or even prefab variants of it
Interesting. Thank you! π
Do they move with the character?
No, in fact they are just wrong
Why is Vector3.forward pointing down??
probably for * 0.4
Is the cube rotated?
No, its just a wider radius
No.
What is he supposed to do?
Well, if the enemy is in the 'Defend' state, he'll go to one of the 3 line's end.
But this way, its just in 1 place
Added a vector that adds to the other, but its still in 1 place
If you want it to move to where the line ends you can use SetDestination, but it will go straight
you are using global postions
use the actual player transform
How do I not use that?
Player.Transform.forward
I use that
not vector3.forward
show me Hierarchy of player
what what it has on it
if the player doesnt rotate, the debug will never rotate with it
also check what player is in your code and check if is actually is a transform
It is I checked.
The problem is not with the rotation. It is with the position.
The lines should move with the player indicating its forward position.
But I might have to just add the player's position vector to the end?
can i see the Hierarchy and not cropped out
thats the inspector
I kind of got it
I made an offset indicating the player's position excluding y, and then adding it to the end position of the line
Why only 1 selected sheep spawn if i select 2
foreach (GameObject obj in gameManager.SelectedItemsList)
{
if (!instantiatedObjects.ContainsKey(obj))
{
GameObject instance = Instantiate(obj, SpawnPosition, obj.transform.rotation = RandomRotation);
instantiatedObjects[obj] = instance;
}
}```
They're the same prefab presumably
and your code here is guarding against having more than one object spawned from the same prefab
how i should change it ?
You're also modifying the prefab's rotation here which is a bad idea:
obj.transform.rotation = RandomRotation```
i.e.:
GameObject instance = Instantiate(obj, SpawnPosition, obj.transform.rotation = RandomRotation);
Should change to:
GameObject instance = Instantiate(obj, SpawnPosition, RandomRotation);
get rid of that if statement.
if you want to actually track spawned objects per prefab you would need a Dictionary<GameObject, List<GameObject>> and then you could theoretically limit it to some number N of spawned obejcts per prefab if you want (with some additional code)
but right now your code is limiting to one object per prefab
guys how do i approach a big project that i want to replicate
explain
this is very vague
replicate what exactly?
also is it code? cause this is code channel
like i want to create a replica of a level from zelda
and i have a example small project in github that my guide sent me
for learning practically
so whats the problem ?
I dont know where to start
its like what part should i focus first
cause like its hard to know where to start like what thing
it really depends how much you know about unity & code
like the scripts
making a game is no easy task , lots of different systems in play together
i know enough but i want to get out of the tutorial bubble
yea i am not a newbie
break down bigger problems into smaller ones easier to solve
I know design patterns,codes,etc etc
yea i have tried breaking them down
its just where do i start
but do you have *practical * experience
yes creating small projects
it realy makes no difference where you start, as long as you start
get things in motion you will worry less
thinking too much leads to "paralysis by analysis"
when that happens to me I just start chipping at it , as π§ as that is, it works
starting anything at all gives your project "momentum"
from there to me just snowballs , I dont even think about it anymore and just churn out code
well..like a marble sculpture, in the beginning its just a block of marble until you start "chipping" with a chisel / hammer
yea i mean thats a good way of thinking
really good example of how things come together sometimes
well, subtractive art anyway.. for additive you could say the first glob of paint on the painting
Hi, I have a problem with my tools and weapons. All of my tools and weapons are SOΒ΄s which have different stats, however one of them is Durability. I want to know how to remove the object from my inventory whenever it breaks. The problem is that when I reduce de Durability counter with each hit, I am reducing the SO stat so I am facing the problem that I might have to create a new class of tool that has a durability float and add that specific class into a different List on the Inventory Manager, is there another way to solve this?
Max durability and current durability should be different variables
And current durability doesn't belong on the SO but on a runtime instance
but those two variables are supposed to be in the SO? In that case whenever I reduce one, it reduces for ALL the SOΒ΄s
Why would the database need to know the current durability
yeah, doesnΒ΄t make sense but I donΒ΄t know how to solve it other than creating a new class with the current durability variable and that could make me redo lots of stuff
You should already have a class representing the actual thing in the scene that reads data from the SO
so I should have ToolData and Tool Object, ResourceData and ResourceObject for example?
even if they dont belong in the Overworld
It doesn't need to be a MonoBehaviour, but there should be a "Not ScriptableObject" class you can pass around and modify that represents that specific thing in the game
Okay, thanks a lot for this help
Kinda new to coroutines and delays but... I can't see any delay even after this
yeah cause the coroutine isn't doing anything
so you put the loop in the coroutine
Starting a Coroutine doesn't NOT delay the current function
Like this?
it starts an "async"-like function, as it runs "on the side" (technically isn't but its very fast)
did you read what I sent?
Reading that rn
So... from what I've read sooo far... The coroutine repeats every X number of seconds or frames?
right now it does the loop. Starts a new coroutine, waits for time and does nothing.
you're not using it correctly
My character is doing some crazy stuff when moving towards the camera. I am using cinemachine but how is the character blocked by the camera?
Ok ok. I'll read more the doc and then implement it. Thank you sooo much!
more specifically. look where they placed their Yield
also
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
has further examples
they are a bit more practical
huh ? cameras cannot block characters, unless you had some type of collider on it
Hey guys! I want to make a top-down 2D world map like you're playing Risk or something that lets you select individual parts of nations on a map, but I can't find any tutorials that teach me how to make something like that. I'm an absolute noob at game coding so any help/tutorials you could send would be really appreciated
World Map Strategy Kit 2 is the closest thing to what I'm looking for, but I don't have 100 dollars to spend and I want to make everything myself if possible.
you can use OnMouse events to detect for clicks and stuff on 2d sprites for example..
just need to create some buttons that look like different pieces of the level
can also raycast onto a texture to find exact coordinate you're on , match the color to specific regions or something like that
maybe use SVGs for the shapes?
yeap, could do that.
gonna make my first ever FSM, wish me luck
I believe this part causes the weird character rotation.
very probably, you can read Euler angles but you cant actually use them for much
good luck
gonna keep it simple:
one FMS "brain" script that can change between states, let other scripts inherit from it, and one state template script which is going to be a scriptable object, other states can inherit from it
Thanks, guys- I also found a good tutorial, too
@rich adder Once again, Thanks! Btw... how's this animation?
you mean the tweening UI elements or the player animation? the playeranimation is glitchy..
looks good, maybe a tad slow
also #archived-game-design or #1180170818983051344 for opinions
Yeah no shit π. The Player Animation, we just rushed that π
its just missing a keyframe or so it appears
the loop back to the start is glitching
yeah player animations needs bit of work, maybe copy the last frames and invert them
but yea, if he talkin about the card stack. it is really slow imo
it should be really close to instant.. (players hate waiting for stuff for no reason)
If I add this, my A and D Inputs rotate the player too strong. Is there another way to calculate the rotation in relation to the cam without using eulerAngles?
I added the option to make it run faster so that's not an issue
But the main thing is I at least know coroutines a bit now
most button type animations should be between 100-500ms good rule of thumb
almost instant.. but not exactly
theres methods that use only Quaternions..
i tend to use AngleAxis alot for things like cameras
heres my FMS system rn, lemme know if you see any problems with it
state script: https://pastebin.com/ZsxPLSgh
FMS script: https://pastebin.com/nN8tLHQn
This isn't really about the code itself, but it is FSM not FMS, Finite State Machine.
Finite Mate Stachine
LMFAO im keeping it this way for the funny
finite at freddy
Hello there! has anyone worked with custom css and html for itch.io pages before? im looking to ask about adding some custom html classes or id to edit specific elements in my pages, has anyone done some of this before?
this isnt a unity coding question..
oh sorry is there a channel for game page related stuff?
closest would be #1157336089242112090
but you're more likely to get a response in a more general game dev server or somewhere specific to web dev/html+css
yeah i guess something like web related servers would be useful! haha there's really not much documentation on itch page customization from what i've searched
real simple question why do we multiply the sensitivity with time.deltatime when making a mouse looking function
you're not supposed to. people teaching you to do that are wrong because mouse input is already frame rate independent
cause its wrong
I knew it
thank you all
one more question tho
what are quaternions
I've been trying to find that out for tha past 3 hours
it's a 4 axis structure to represent complex rotations. you don't really need to understand them, there are helper functions that let you use euler angles which are the angles you are already familiar with
thankss
they are a datatype that holds a rotation
just like a Color is a data type that holds a color
Quaternion would have been better named in the API as "Rotation" simply
I feel like if they'd done that there would be even more people improperly using their members as euler angles. at least with the data type being called quaternion it's easier to look up what they actually are and see that they are not expressed in euler angles so fewer people abuse them
I feel like it's hard for that to happen more than it doesnow
if it had a simple name it could trick beginners into thinking that its something simple that they can just mess around with
you can use github pages if you want to write your own page completely. but people actively scroll through itch to look for fun indie games to play
whereas with quaternion, beginners can look it up and see this image, realize that its something more complex that they should tackle once they have more experience
netlify/vercel lets you deploy your unity app quickly as it doesnt have a size limit, you can then embed the netlify/vercel PWA into a github page
that's how im doing it rn
would never pay for netlify/vercel but they're a good free option ig
yeah i'm currently editing an itch page for an asset pack and i'm struggling to find a way of adding classes to specific elements to edit them individually in the custom css and it seems like itch does not accept adding custom html, my knowledge of html and css is very very basic so im having a hard time finding another way to do what i want to haha
are you able to embed a custom page into itch?
if so embedding a custom github page could work out
please don't do this to me
I just installed unity
please
itch uses markdown.. and its own css https://itch.io/docs/creators/css-guide
as with all websites like that that grant you some customization its never completely customizable
That's the thing though. Beginners are really focused on the XYZW part. But Quaternions actually ARE something really simple they can mess around with. Just not by looking at the XYZW components. They are simple to mess around with using:
- The * operator
- The static methods in Quaternion such as Euler, FromToRotation, Inverse, AngleAxis etc. @steel hull
youll learn it eventually but dont be too nervous
like this is nonsense because day to day I don't even know or care about this. I just use the API
and it's easy
i posted a visualisation of each type of rotations a while back give me a sec
nah I'm just trying to make the learning a bit more fun with jokes and stuff
you really don't need to understand the underlying data, just the helper functions i pointed out that are also listed in that page i linked
People scare beginners away with the "4 dimensional" nonsense and really Quaternions are easy when you just ignore that stuff
and use the API
i mean same idk anything about quaternions i just know like 2 lines that i memorize
Are you telling me I can't embed a malicious JS script in my itch page?! 1984
i think everyone besides math majors.. just use quaternions..
don't need to understand em to use em lol
Go look up quaternions and transformations from a 1977 PDF from NASA, there's like 12 different matricies to create a quaternion π
Honestly when it comes to quaternions, I just tell people to get a basic understanding of gimbal lock and that's it
There are a lot of handy visualizations out there
that and you combine quaternions by multiplying them.
what does clamp exactly do like limit?
it returns a value between the clamp min and max
returns a number closets to teh limit it falls in
oh so if its over the max it returns the max
yes
float Clamp(float value, float min, float max) {
if(value < min) return min;
if(value > max) return max;
return value
}
minor spelling mistake
I am learning π
thank youu
Its easy for me to understand most of these because I was originally a roblox developer but I feel like unity is much better
not to reach users but in any other way
yeah I know thats why I switched
nah like studio