#💻┃code-beginner
1 messages · Page 688 of 1
So what? 300 lines is not long
If you don't share the full script it's just a wild guessing game as to what's going on
it could be anything
I'm moving my projectile with Vector3.forward
When I tried to implement rotating with LookAt and RotateTowards - the projectile was moving in the different direction, but the model was not rotating at all.
That's the issue
Alr here it is https://paste.mod.gg/kqxdkozoerum/0 I will say tho I did narrow the issue down to the IEnumerator function basically I want my pistolarms to rotate down (to show a reload transition) wait there a bit for reload duration and then go back up but for some reason I reload twice and (I go down and up and then again instead of going just down and just up)
A tool for sharing your source code with the world!
I'm moving my projectile with Vector3.forward
This doesn't make sense. Vector3.forward is just a vector, not a way to move anything.
When I tried to implement rotating with LookAt and RotateTowards - the projectile was moving in the different direction, but the model was not rotating at all.
Sounds like you are using Translate and you are simply rotating the wrong object
You will need to share more details about your code and how your hiearchy is set up
Bro I just said I was using Transform.Translate in the previous message. You are the one who is not seeing sense.
You have code in HandleAiming that is trying to rotate the object at the same time as the reload animation
they will fight with each other
The rest of the message is the important part
especially:
You will need to share more details about your code and how your hiearchy is set up
damn u were actually right thanks dude
That's why I asked for the whole script 🙏
thx bruh never question the pro i guess
I followed a tutorial to make a movement system, then another to make a turning system, the problem is that the movement is global not local, so when i turn it isnt moving correctly.
Is there any fixes to this?
using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour
{
[SerializeField] private float speed = 5f;
[SerializeField] private float jumpHeight = 2f;
[SerializeField] private float gravity = -9.8f;
private CharacterController controller;
private Vector2 moveInput;
private Vector3 velocity;
public Vector2 turn;
void Start()
{
controller = GetComponent<CharacterController>();
Cursor.lockState = CursorLockMode.Locked;
}
public void OnMove(InputAction.CallbackContext context)
{
moveInput = context.ReadValue<Vector2>();
}
public void OnJump(InputAction.CallbackContext context)
{
if (context.performed && controller.isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
}
void Update()
{
Vector3 move = new Vector3(moveInput.x, 0, moveInput.y);
controller.Move(move * speed * Time.deltaTime);
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity*Time.deltaTime);
turn.x += Input.GetAxis("Mouse X");
turn.y += Input.GetAxis("Mouse Y");
transform.localRotation = Quaternion.Euler(-turn.y, turn.x, 0);
}
}
!code 👇 use the links
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
📃 Large Code Blocks
no he saying like u gotta go on one of the sites and then make a new file the site will give u a link
also misclick i didnt meant to react btw 💀
why though, would it not be easier to just post it
or is it just to stop walls of text
its for making it easier to read, its a pain to read giant wall of text on discord especially on mobile
we have the system for a reason..make it easier for others to help
anyway the move there is wrong, you're using input values as move direction which will give a world coordinate.
Also Move() should not be called twice in the same method
Hello all. So, I am following a Unity tutorial on how to make a 2D platformer. It has been going great, tbh, and I am almost done, but I have encountered a problem here.
So, I have a script for Player Movement that has a part about turning your sprite around when you go left or right. In the tutorial we just added a speed trail sort of effect when you get a speed boost.
The problem is, I notice the transform.localscale here is setting the scale of my particle effect system to 5, because I early on set the scale for my player to 5 (The Particle System is a Child of the Player right now).
So the problem basically is -> When I am sped up and turn left, my particle effect trail suddenly gets 5 times larger, and stays that way. How can I stop this?
classic mistake of scaling the Root of the player rather than just the graphics/visuals, they should be seperate gameobjects first of al
Yeah it was a mistake I made early on. And have been compensating for it since lol
put the graphics/visuals on a child object of player and keep the root at 1,1,1 for player. Then you can scale the Graphics child to any scale you want without it affecting other children of player and rotations if scaled non-uniform
btw is there anything i can do to make the current player movement local instead of global that isnt rewriting the whole thing
I am not exactly sure how to go about that
wdym how? which part of it are you confused about, i pretty much explained the process lol
'Put the graphics/visuals on a child object of player' - I don't know what this means, or how to do it. Is the only way to set my scale for my player back to 1,1,1?
like so:
hey im working on this "inventory system" which basicly consists of 5 slots. picking items up until the inv is full works great, also animations work with it. sadly i just dont know where to start with implementing a scroll feature where you can select the items from your hotbar as it now just uses the last item picked up for its functionality and animations. heres the code i use for this: https://paste.ofcode.org/xX3HiJhjpmhwrzCLv9GHQD, https://paste.ofcode.org/CpjGq39Fwn4zeLxhVNNeZB, https://paste.ofcode.org/346D7WDUp2ne9xGd9Zdt5Vc
Just make an int variable to track which object is currently selected and base everything off that
is c# considered easier than c and c++ ? cause that is the experience i am having so far, or is it just because unity does a lot of the work for you
im pretty sure it is yea. atleast easier than c++ cant really talk about c
i tried learning c++ few months ago absolutely hopeless
some of my friends tried it but they also gave up pretty quickly
i personally like c# as it shares a lot with java which is a language im relatively used to
c# also feels pretty similar to luau to me
only thing i dont like is putting ; at the end of every line
i like that actually
dont really like that at python
but theres a lot of other weird things going on with python syntax so...
i do not like python very much
lua with none of the good stuff it feels like
can you tell i like lua
as mentioned before not really my language but i can understand why you would prefer it over some other languages
what kind of syntax is this
that's an 'attribute' https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/reflection-and-attributes/
thank you
even though variables default to private, is it still convention to write private before every declaration of a private variable?
or personal choice
Personal choice
I used to be on the side of 'don't include superfluous information' but when you end up switching between languages with different defaults, it's nice to have things always be explicit
i have an array. i know you can use array.min to find the minimum value. how can i find the ** location** of the minimum value in the array?
Just loop through the array n check
There is an array method that will search for the index based on the value . . .
I definitely recommend the lost art of "write a for loop"
Less efficient
Must optimize
I have an enemy and a player set up and for some reason, when I jump on top of the enemy, I take damage, but I take no damage if it is above me, or touches me from the side. Any ideas?
show code + setups in scene
guessing game would get us nowhere for a while
by setup I mean show triggers / colliders etc
Impossible to say without more context
could anyone tell me how i can make controller.Move(move * speed * Time.deltaTime) work on local position, controller is a charactercontroller and move is a vector3 that has the move direction on it
just parent whatever has the controller to a root object
Convert the vectors to local vectors with methods on the Transform.
And back, as needed
idk how to do that, would i be able to find it online
Of course
how do i avoid the yandere dev if elseif elseif elseif thing

in the og yandere dev thing, that can just be shortened with a single operator or a for loop.
afaik though, it completely depends on the scenario
You'd have to show a specific example
coroutines cost when just exist, or when are used?
is there a reason why my gameobjectlocalizer is empty?
how do you make appearing bulletholes texture in a wall?
decals?
If it's not called/referenced anywhere, it's not included in the program binary.
thank you, i was gonna use a plane with a texture before you said that
i mean
i have a player that if performs a combo, it does a coroutine
the coroutine lags whenever it exists, or only lags when i do the combo?
It doesn't lag. It consumes processing resources. Only when it's executed.
When you call StartCoroutine and as long as it didn't complete.
but isn't processing resources lagging?
i mean, if the pc's slow
or is just very rare to cause it to lag?
like the radiation of a banana
No. If you uses that definition, then it's fair to say that your whole program/game is lagging, since it's using processing resources
no i mean, not using processing resources, i meant, abusing of processing resources
like a lot of coroutines corouting (?
The conventional definition of lag is a spike in performance that. Causes discomfort to the player.
A lot of any kind of running code would cause lag, yes. It's not unique to coroutines.
oh
interesting
i mean, cuz i been told coroutines have a cost
i mean, what's the danger of using coroutines?
or i can make coroutines as i want?
Everything has a cost. There are no dangers if you apply common sense to coroutines same as to the rest of your code.
There is some overhead for a coroutine, but it's normally negligible, so you can consider it the same as running that code in Update.
It's more about the contents of the coroutine, rather than the coroutine itself.
Can anyone help, I'm trying to make my enemy move in it's current direction.
rb.MovePosition(transform.position + (transform.forward * (MoveSpeed * -1) * Time.deltaTime));
This is my current code
btw, im pretty sure you can do -MoveSpeed instead of MoveSpeed * -1
also that code looks fine to me so far, are you having any particular issue?
hi im a complete beginner but when i try to add a controller to this it gives me this error does anyone know why thanks
You have two assets with same GUID
How did you copy the SampleScene scene?
You should only copy files from within the unity editor
someone knows how to fix this weird glitch while making a 3D tilemap?
Not a code question, but they look like they're overlapping . . .
fr, wrong chat
but anyway, they overlap because they got rounded corners that "escape" the single tile, so, when it's hollow on the side of the tile, it's corners get visible
but i just found a way to do it, nvm
thank you 🙂
Why does my UI buttons lose reference to the "LanguageManager" after reloading the scene? I have set it up as DontDestroyOnLoad but that didn't help.
I have this on the object
private void Awake()
{
if (Instance == null && Instance != this)
{
Instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
I assume it's because the LanguageManager is now a copy, instead of the original object, but I don't know how to fix it
is there a reason this object need to be preserved when reloading the scene? if not, then don't use DDOL and it should work just fine
I think we need that object to persist, because it acts as a "global" variable for every single UI element to localize their texts
Maybe there's a smarter way to do it
Basically every single text element has some script like LocalizedText that is just a simple switch based on LanguageManager.Instance.currentLanguage
why not use something like unity's localization package? also it sounds like you've probably hard coded the strings so why does that even need to be an instance method rather than just a static method?
Too late to change it to something smarter, but probably it doesn't even need to inherit from MonoBehavior now that I think about it
You could probably just use a scriptable object if there's data that needs to be written in inspector. At a certain point youd just be remaking what the localization package already does.
I think this was a bit of XY question...I have done a quick hack to fix this. The OnClick event now fires a custom event.
public class LanguageButton : MonoBehaviour
{
public static event System.Action<Language> OnLanguageButtonHit;
public Language language;
public void ChangeLanguage()
{
OnLanguageButtonHit?.Invoke(language);
}
}
Hi, I am making an audio manager and was wondering if there's a way to apply filters in the correct order?
Afaik, the order matters.
So I was wondering if it's possible to reorder the components instead of destroying/adding them each time the audio plays(audio manager can change at runtime so I'd have to refresh each play).
Please @ me and thanks in advance!
I am also open to alternative suggestions, this just seemed like the most logical thing tho.
I would say this is more of a code question as I am asking how to code it, will send in #🔊┃audio if needed tho.
https://paste.mod.gg/wywkqtamryaa/0
I made this script for an object that would do something if a ray hits a object that has the tag Gun but it wont get it and I tried this in another game I had and it worked fine. Im not sure if its the object but I think it since the object that did work had 1 part while the other had a part with many children in it.
A tool for sharing your source code with the world!
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Do you see "click" printing in the console?
Yes
I also added a log so if it did see the tag gun it will say it but it doesnt and I have confirmed multiple times it has the Gun Tag
Add a log inside the deepest if block
And print the name and tag of the hit object outside that if block.
And share a screenshot of the object that is supposedly hit.
Take a screenshot of the whole object inspector.
The hit object doesn't have a tag according to that log.
I might have a missing
component
I don't see a collider. This is not getting hit.
what collider should I add
Any collider that you like(as long as it's a 3d collider)
You probably want it to match the shape of the object.
I tried a mesh but still wouldnt do it so I tried a box collider and it works
A mesh collider needs a mesh assigned obviously
theres lots of meshes.
Well one mesh collider can only have one mesh.
But if a box is good enough, you should use it.
do I just add multiple? lol
You can, but it's also a good way to kill your game performance
What would you do?
Should use mesh colliders scarcely
Use a simple collider if it is good enough
Collisions don't need to be 100% accurate.
Usually
I might just use one mesh collider for the grip of the gun, itd make sense
Note also that mesh colliders(non convex) can't be moved.
So if it's a moving object, you have to use convex, but ideally, simple shape.
bump
does anybody know why this script isn't moving the enemy?
rb.MovePosition(transform.position + (MoveSpeed * Time.deltaTime * transform.forward));
(sorry ">:3c")
you need to put it in update and use if key pressed to move
ok thanks
Where is that code in the script
What function is it in
void update()
Is that how you spelled it in the code
void Update() should be or FixedUpdate
ok
yes
Then that is your problem
Unity does not have a update message. Capitalization matters.
oh, I though you were talking about the rb.MovePoition script
sry the update one is in caps
You can just google the MovePosition method and you will be redirected to the example of use
bump
can you explain this a bit more
I add audio filters to the object with a source from a script.
I was wondering if there's a way to reorder these filters when they change or if I have to delete+add them each time for them to match the order defined in the list.
ohh so like filters are components ?
maybe an editor only script ? I don't think there is a way to do so otherwise
I see, thanks!
found this https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ComponentUtility.bindings.cs
use at your own risk lol
Thanks, seems like an editor only thing tho, not what I need.
Ig the filters are just poorly designed atm, afaik they discontinued them for some reason and expect you to have an audio mixer for each source that should sound different, average unity stuff really.
yea the closest thing Ig you gotta do Destroy and Add at runtime
never messed with it much so I suppose so, I thought the mixer had their own thing with an array or something you could reorder.. sucks..
ye mixer does, this is applying to object with sources directly tho
but yeah, thanks for poitning the editor thing out, might come in useful at some point
i did find a few threads mentioning this used in an extension fyi
guys what random.randomRange do diff than range?
can you explain please
like normally i use Random.range(1,10) as example to get random number but i noticed function called RandomRange
There is no RandomRange function in the Unity API
idk
see on the right side what is says
kinda the same as random
read again what it says
Yeah, RandomRange was the old way to call it, it's been replaced with .Range
oh thanks <3
no, not that. First of all, any functions that are deprecated or obsolete are not to be used, secondly the +1 overload only means that the same exact function exists with different parameters, in this case floats instead of integers.
Functions such as "Instantiate()" can have several overloads, given the variety of parameters
what a random post
oh
how do I call a method that is in another script
Choose the best way to reference other variables.
Hi I'm trying to create an interactable water and I was following this unity tutorial I found online. For some I get an error for custom editor is there a namespace i am missing ?
this is the tutorial https://youtu.be/TbGEKpdsmCI
Show your Support & Get Exclusive Benefits on Patreon (Including Access to this tutorial Source Files + Code) - https://www.patreon.com/sasquatchbgames
Join our Discord Community! - https://discord.com/invite/aHjTSBz3jH
--
I had......SO much fun working on this project... Despite having to completely scrap my first approach!
We're going to use ...
What does the error message say
You have to fix the errors from the top first
Show the entire !code 👇 if you need help with it
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEngine.UIElements;
using UnityEditor.Experimental;
using UnityEditor.UIElements;
[RequireComponent(typeof(MeshFilter), typeof(MeshRenderer), typeof(EdgeCollider2D))]
[RequireComponent(typeof(WaterTriggerHandle))]
public class InteractableWater : MonoBehaviour
{
}
[CustomEditor(typeof(InteractableWater))]
public class InteractableWaterEditor : Editor
{
}
Hey guys im new here. Any advice on how to get your hand on learning material for noobs?
im familiar with programming but not unity itself
!learn + materials pinned in this channel
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I provided the code
you will have to use a seperate script for the customEditor i guess
Show us the console window from the Unity Editor
so I have a big array of coordinates that I need an object to follow, each line has an X coordinate, and I want it to go to the first line on the first frame, second line on the second frame, etc. how do I go about doing this?
what type is you array?
float
i am assuming yout got a 2d envoirement there
we need to know that actually since we cna use MoveTowards or something similar
yeah its 2d
so what you could do is to have a int for the current element. everytime you reach the array element you raise this int and use Vector2.MoveTowards.
honestly right now im having trouble with putting the values in the array
if (Vector2.Distance(yourArray[curr], transform.position) < dist)
{
curr++;
if (curr = yourArray.Length)
{
curr = 0;
}
}
transform.position = Vector2.MoveTowards(transform.position, yourArray[curr], Time.deltaTime * speed);
``` *pseude code
oh wait i had to change it to a double
i´d say use a list or Array of Vector2 instead
why not just use a pair of x and y (Vector2)
basically it stems from a list (not array) that i had that would record the x position of the player every frame, then I put the values of the list into the array, and i did the same for Y
I think it may have something to do with thins?
here is what it currently looks like
it is UnityEditor only without the dot
and we alreasy said, you have to seperate the CustomEditor script and the MonoBehaviour @still ingot
Wrap anything Editor-related in #if UNITY_EDITOR or make a separate script file for editor code in an Editor folder
And what exactly are you trying to accomplish with this? Why do you record X and Y separately? Why are you putting the elements from a list into an array?
why my camera is really zoomed out
because you use FreeAspect chose the screen size
where
below the Game Dispaly1 FreeAspect, and set the Ortographic size to make it closer
i mean my camera zoomed out when i add 2d camer
You mean change perspective to Orthographic?
maybe but when i change the Orthographic size still like this
Try to check MainCamera maybe it is avtive one
the main camera when h change anything doesn't display in the game
i want too look like this
You delete cinemachine camera but your MainCamera is alive so looks like it is active one select it in hyerarchy and change settings
Orthographic size property works fine but i want to change the y axis
the Y axis will be the axis of your screen resolution select resolution here
currently u have free aspect
i don't know what i do but it's work 😂 😂
Thanks for helping me to try solve this problem.
im new to meshes trying to understand tmp mesh animation
textInfo is a TMP_TextInfo
what these 2 lines do? is it get material of that one character then storing all 4 vertices of that character into var vertices ? and why also has to go through the material to get it ?
int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
vertices = textInfo.meshInfo[materialIndex].vertices;
Hello, I was wondering if async and await have an equivalent to WaitUntil in coroutines.
Pretty much for the timelines in my game I'm having them be managed by coroutines, but the character animations are going to be separate with async functions as I don't need them to be managed frame by frame, and I heard that coroutines can get really messy if you don't need them.
UniTask use both features of Async and Coroutines
UniTask?
only just heard of that now
So instead of using coroutines and async, I should just use UniTask?
its a good idea to use unitask, it allows you to glue together coroutines, async/await, dotween, unity/c# events, observables/reactive, promises, channels and a bunch of other things to do whatever fits the problem at hand best
Fairs, what I have at the moment is that my timelines and progress bars are controlled by coroutines, and I was thinking of having NPC animations be Async. So I should just switch it all to unitask then?
I haven't built the game yet, I've just been figuring out how to do the individual features first, so that I can put it all together
it might be a good idea to get a good understanding of "asynchronous" logic flow and various ways to implement them before jumping onto async/await
there is a lot of potential for confusion when not quite having a correct mental model of async, coroutines are so primitive and easy to understand that you cant do much wrong with them, unitask however has a lot of features
Ah ok, I might as well understand async separately first then, before jumping into unitask? I can always refactor it later anyway
I did watch some tutorials earlier and have some form of understanding, like I could just have a boolean within an async where if it's true, yield on another task, before returning to the other async?
Yeah Coroutines are piss easy, so useful tho
Using UniTask's provided delay/yield functions should make it act just like a coroutine but you do have to handle "cancellation" yourself (or use the cancellationToken arguments for Delay/Yield)
Guys do u recommend cinemachine to make camera follow object or should i code camera position
Idk which one is efficient for a game
I'm working on a replay system and I'm trying to figure out how to store times. I want to ask if I can reliably count physics frames as key frames for input
whats wrong with Update
Inconsistency across devices
huh?
I had planned to do something like this
int framesPassed
void FixedUpdate(){framesPassed++;}
and every time I store an input, I store that value with it
Update is fps reliant I guess
Time.deltaTime comes in
You might skip some input if you do that though.
have you seen this before ? its really good https://youtu.be/Bb8Rdivmx8U
Check Out Bezi Sidekick - https://www.bezi.com/sidekick?utm_medium=youtube&utm_source=gdg
Grab the Unity Package for this episode (includes a bunch of bespoke assets from Cabs Of Chaos) - https://www.patreon.com/posts/117914143
Chapters
00:00 - Intro
00:53 - Titles
01:40 - Sponsor
02:41 - Project Overview
03:20 - Creating The Replay Manager
04...
No, I'll watch it
yeah his videos are usually on point, might be worth taking a look for inspiration / idea on the process
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Check Out Bezi Sidekick - https://www.bezi.com/sidekick?utm_medium=youtube&utm_source=gdg
Grab the Unity Package for this episode (includes a bunch of bespoke assets from Cabs Of Chaos) - https://www.patreon.com/posts/117914143
Chapters
00:00 - Intro
00:53 - Titles
01:40 - Sponsor
02:41 - Project Overview
03:20 - Creating The Replay Manager
04...
what did he do there
how do you make a custom object like that
I've got no audio so couldn't hear any instructions if presented from the video but it would seem he created a script and made it inherit Scriptable Object. With the attribute above the class, he was able to create a Scriptable Object instance like how SOs are meant to be used.
tldr he created a scriptable object and scriptable instances
https://docs.unity3d.com/6000.1/Documentation/Manual/class-ScriptableObject.html
ahh alright
and while unity is running are all assets stored in memory? or does it have a smart system to know when to store stuff
im guessing videos for eg aren't stored in memory until they are spawned in game or manually pre loaded
Which assets?
these
Which ones? Game objects that aren't in the scene are likely prefabs.
I see folders. You can access these locations using Window's Explorer and whatnot as well
well just as an example in a script if i spawned a prefab ingame would there be a wait time while it loads from disk onto memory to then have it ingame?
Directly: Via build settings scene registry and anything inside /Assets/Resources/
Indirectly: Any asset that is referenced in any direct asset
For scene stuff Unity will load related indirect references when the earliest direct reference that uses them is loaded. Unloading depends on a few things
There probably would be but it'd likely be mediocre and nothing to worry about. What were mostly concerned about with data are when they're collected by the Garbage Collector. This can take some time.
right so if a script has a prefab referenced and that script is a component of a game object currently in the scene, the prefab is loaded onto memory as well yea?
I'm not entirely certain.
Nitpicking your wording, instance of script rather than script
an instance of script
That prefab is not loaded because in that scenario that’s a reference to a instance of a prefab and not a reference to the prefab asset
Yes
The assets are instances (in a sort of way) that aren't in the scene iirc
what happens if i spawn an instance of script with a whole bunch of assets referenced, and it can't load them all onto memory by the time that script wants to spawn one in
Their in a hidden secret scene yes 😄
References are cheap
If you can access that instance of script those assets would already be in memory
Values are more of a concern but they aren't really anything either
right...
is there actually a hidden scene where everything is preloaded?
Ye
damn
HideAndDontSave
best solutions are the simplest
what are values sorry
Though things only get put in there when the related direct reference loads
oh
im not concerned about memory usage here
more about like loading times and stuff
talking to @ivory bobcat btw
ive just realised a problem with my questioning
to have references you would need an instance of script, which means when you spawn in a script it's not gonna have those references
and whatever method u use to get a asset on disk referenced in a script is probably where loading times are right?
Thats one of the reasons I was nitpicking 😛
yes
Which is either
A. scene loading
B. Initially when it loads from /Resources/
C. Adressables/AssetBundle related
DEFGHIETC. Niche stuff like explicit texture, model, audio importing etc.
Usually scene
And usually it’s the heavier stuff inside these like textures and audio
Where can i find a good youtube tutorial? i've been through the inbuilt 2d one and idk where to go from here
youtube
i would say if u been through a whole tutorial already youre ready to start messing around in unity
you know your 4 Fs
4 Fs?
that's 2 Fs
good i was testing you
i can do maths 👍
actually though if you want to progress you must start reading documentation it will teach you everything
do i haveto
Can also go to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
just come up with something you want to make, start from the start, and by the end you'll know what you have to know to make it
i want to make a pill walk around, first i look up how to move the pill, how to make the pill stand up, how to make the pill jump, maybe along the way i'll learn how to make a camera, boom, i know more than i did before
all in documentation?
I think making it stand should be the first step 😭
forums and documentation and youtube
probably lol
Look.. just find a good tutorial that goes completely through the game development life cycle. After finishing the tutorial, hopefully you'll have the skills to design, create and release your game.
im guessing there's an extensive supply of info lol
Thereafter, you would mainly lookup videos or document on how to do specific tasks that would make your game the way you'd like to make it.
@ashen pier i can give u 1 advice
yeah
dont quit, making games is the most addicting thing you will ever do in your life
once you get there
ok cool haha
im super into storytelling and puzzles as well which is cool
should help
yes
fighting fleeing feeding mating?
or fight flight freeze fawn
damn there's a few of these
forget it
it's so hard to talk here like every 2nd thing i say is blocked because it's "out of context"
Then don't say stuff that is out of context. This is not a friendly social chat.
mr serious over here
anyway moving on
the documentation will help with C#, but how can i learn more about the actual engine and stuff?
ok so for eg i want to know about game objects
i go onto google i look up "unity game objects"
The manual.
and it gives me this https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.html
they are right though. this server is more of an alternative to the unity forums as opposed to your average discord server
You're looking at the script reference, you want the manual
its a button on the script reference my bad
following through a tutorial, it says to import a new asset but when i right-click that option doesn't appear.
you should just be able to directly drag the file into the project. not sure why the option isn't there though, might be a mac thing.
probably lol
do sprite files need to be a specific type like .png or can they be stuff like .jpeg and .webp?
wasn't actually sure myself but according to the docs
unity supports these files types:
.bmp
.exr
.gif
.hdr
.iff
.jpeg
.jpg
.pct
.pic
.pict
.png
.psd
.tga
.tif
.tiff
for textures
f1 f2 f3 f4?
oh weird, it's in a slightly different spot
huh. guess i'm blind
same spot for me
same here it seems like lol
might be a unity version thing
yeah maybe
that's the neat part, you dont 
im pretty sure it's just sorted in alphebetical order by default
from there you can just sort your files into folders
sure ok
is there a way to make the text/ui bigger?
it says there's no program to open scripts, did i miss something when installing?
Have you installed your ide yet?
what's that
Your application to write scripts with
The two free common choices are Visual Studio or Visual Studio Code
yeah i'm on mac so regular VS isn'tsupported
Next you would need to configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Yours would be the blue one VSC
why does unity need an external IDE? is there any reason why it can't have its own one?
It used to have Mono Develop but that's not a thing anymore
https://en.m.wikipedia.org/wiki/MonoDevelop
You simply need to configure your favorite ide (limited to a few choices) to work with Unity and you'll be all set
idk which is my favourite since i've never used one but i'll go with VSC
C# looks a lot like java
Some say it's the hybrid child of C++ and Java
They're all part of the C family language so they're look similar in syntax
good to know
The tutorial says a list should show up here when i write the dot
Did you properly configure your ide? There's quite a few more steps than just installing.
Step 3
this everything?
I suggest installing the Unity extension like instructed before step 3.
What's that warning symbol with the Unity extension?
Do you've got any other errors in VSC? (usually in the bottom right)
Sometimes folks forget to install the .Net SDK
not that i can see
Close the ide and double click a script from within the Unity Editor
You need it. Try clicking the Get the SDK button
You may need to reboot the ide
Close VSC and double click on a script from within the Unity Editor (scripting folder etc)
still no list
Are there any more errors in VSC? Can you take a screenshot of the ide open?
Click on the file tab (you're currently in the extensions tab)
No, you don't need to be signed in
just redacted my name lol
Looks like you're all set
Lists are a part of the system collections name space. You ought to be able to import the namespace after typing the text.
this is what the tutorial shows
What does yours show?
nothing
your !ide is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i just went through and made sure it was configured, idk what's happening now.
i've got all these and the SDK installed.
yes
What they're likely seeing right now: #💻┃code-beginner message
Looks like they've installed the extensions: #💻┃code-beginner message
And last, we had just gone over installing dot net sdk: #💻┃code-beginner message
I'm unsure about what's done on the Unity Editor side or if they're perhaps in the older version of the Unity Editor where VSC has an obsolete/deprecated package of VSC or whatnot (has not been verified)
Or perhaps they just need to reboot the PC (guessing dot net system pathing for Mac might need this)
Have you installed the package from the Unity Editor?
https://code.visualstudio.com/docs/other/unity#_set-up-unity
!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
• :question: Other/None
it says "open windows, packages." where do i navigate to there?
In the Unity Editor, up top, there should be a Window menu
window
ok i had to jump through some hoops but i found it
it's 2.0.23 which is above the 2.0.20 which you need
Did you set the ide in external tools?
i'm trying to find that
So basically, you didn't follow half of the config steps...😅
To open the Preferences window, go to Edit > Preferences (macOS: Unity > Settings) in the main menu.
ok cool
that wasn't listed in the config process though
ok so the visual studio package is updated properly, VS code is the external editor, everything's enabled properly.
still doesn't work.
Can you show us your packages Window? (Unity Editor)
im new to meshes trying to understand tmp mesh animation
textInfo is a TMP_TextInfo
what these 2 lines do? is it get material of that one character then storing all 4 vertices of that character into var vertices ? and why it has to go through the material to get mesh's vertices ?
int materialIndex = textInfo.characterInfo[i].materialReferenceIndex;
vertices = textInfo.meshInfo[materialIndex].vertices;
In VSC is there a shortcut to properly indent and reorder your code?
in a java software i used ages ago CTRL + I would do that
did you read the error
you have code that is trying to use the old input system, through the UnityEngine.Input class. By default the new input system is selected under the player settings.
damn they cant both work at same time?
if you want to use the old input system, change the setting to either use the old one or both
i'm following a 2 year old tutorial lol
you'll find a lot of tutorials that use the old system even though the new one is several years old. its just much quicker for a content creator whos only goal is to publish slop to showcase with Input.GetKey...(whatever key) rather than trying to teach beginners the entire new input system
the new input system has a decent learning curve compared to the old one at least
anyone knows? i cant find any .meshInfo[int] on the doc and they description of them are all blanks
To do tmp mesh animation you are meant to modify the mesh as its made via the events they provide:
https://docs.unity3d.com/Packages/com.unity.textmeshpro@4.0/api/TMPro.TMP_Text.html#TMPro_TMP_Text_OnPreRenderText
I've used this in the past to do a text reveal anim for example
yes it used onprerender event its from this gist https://gist.github.com/CharlieHess/ce73f71aac61fcbe47b692beb6d54490
my question is from line 60
TMP_MeshInfo(Mesh mesh, int size) idk
the .meshInfo[int] thing idk where its come from and why it has to go through material to get the text mesh's vertices
Hmm yea this operator is not on the doc page
Cant find this in the actual code but I presume its geting the vertex list for that material as each will have their own mesh (and there for verts + indicies)
usually its 1 material and 1 mesh but if you have sprites or other tag things it will then be multiple
does each character in the whole text have a different matterial
No
unless you use tags to change it specifically
a font + the settings will be 1 material
i might not know what im saying i hvent touch meshes before
like internal stuff, like they make each character different with different material, so they just reference each cahracter through its unique material ?
it draws the correct character because the mesh triangles are given the correct uvs
if the font has multiple textures it may then use multiple materials
idk whats uv fr
i think i should just accept the way it is for now
you should. Uvs are a core concept for how meshes and materials work so you should read up on that before trying to do mesh manipulation
so get the text character vertices through the materialindex for now
You don't need to touch them but useful to know what they do
the new one seems needlessly complex lol
yeah i seen they go together frequent but by the time i got it, this conversation would be long forgotten fr
UV is just 0,0 in the bottom left, 1,1 in the upper right, and that determines what part of the texture will be applied to the face.
fonts are just shapes
like a cutout sprite
also where's the player settings to change the input to the old version?
edit->project settings->player
thanks
is it better to learn the new one? i don't really see the appeal since i don't think i'm gonna be porting to console or mobile
but idk what it does really 🤷♂️
depends on your definition of "better"
it takes time, but imo it gives you a lot more flexibility - easier to manage and modify once you get the hang of it, and even if you're only targetting pc, you can support controllers easily with it
when does the old input better than the new one? like is there a scenario the new just cant do it ?
no, but for example if you're just bodging to test something, the old system requires less setup
and there is the time and effort cost of learning the input system to start with
i have been just auto using new because its entirely event driven and doesnt cluster the Update()
its entirely event driven
no, it supports polling
input system is really flexible
which kinda contributes to the learning curve tbh
Hey guys I currently have a mouse look script that lets the player look round it works fine but when for instance my mouse is ontop the player it becomes confused on where to look and gets very jittery
Not clossing these with the "break" should be fine right? Cause the break would be unreacheable anyways right?
Just add a condition for a minimum distance from the player before rotating
The jitter makes sense, imagine trying to look at your own head
Correct
Maybe have an if statement that prevents you from looking if your mouse is too close
when in doubt: 
Do I always have to manually chance my variables in my prefabs menu?
I changed them in my code but they do not update in the prefabs at all
You have to change them in the inspector. If you wan't to change them via code you have to make them private.
*non serialized to be precise
What about protected member?
works too, as long as you don't have [SerializeField] attribute
What does it mean Serialized?
basically that it can be saved by the editor
yall
if i have a class that inherits from another
lets say Class B inherits from Class A
if Class B overrides a void from Class A
and i call the void in Class A from WITHIN Class A
does it use the overriden version, or the Class A original one?
I think you should try getting used to changing the variables in the inspector though. It makes it easier to adjust any values. Also, if you have two different apples you won't be able to give them two different Spawn Chances.
the overridden one
I guess so. I'm just more familiar with the IDE
If I keep switching Windows, I often forget what part of code I'm working on
Time to buy a new monitor
If the overwritten function is virtual it will call the override for that instance.
If you instead hide in the sub class this will not work.
more info about hiding: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/new-modifier
is virtual 👍 ty
Just use breakpoints to make note of where you were on the IDE if it supports it , but if you want a second monitor go for it
@stuck yacht Don't crosspost.
okay i am extremely sorry i am new so i think its acceptable ? my apologies @strong wren
Does anyone recommend any beginner unity tutorials
Or anything I should look at to learn
check the pinned messages 📌
In this channel?
Hello Unity, Im using the FPS template and Im trying to access a monobehavior in my namespace but it wont see it. Any help?
in WorldspaceHealthBar.cs
yes and additionally !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thanks bro
is the Script IceBergGames on the same gameObject this script is?
hello
i am new with unity and i was facing a problem .
anyone can u please help me ?
gradlew.bat not found error ads mediation build failed
what's the error? that the namespace isn't found?
have you made sure that the spelling and capitalization, etc are correct?
Yes its all correct.
HellEnemy is in IcebergGames namespace, WorldspaceHealthBar is in fps.game namespace
you need to use the scriptname.
HellEnemy is inherited from BaseEnemy also in my namespace
are you using asmdefs or anything like that
also could you show the declaration of BaseEnemy
you are misunderstanding the issue.
could you show the error? just as a sanity check to make sure we're looking for the right thing
no, the error message
do you get the same message in the unity console?
and BaseEnemy.cs is in Assets, right?
What exactly is going on specifically with the (Choice)_rng syntax? Choice is an enum here but it's not clear to me what the parentheses are doing here, is it casting?
It's a typecast
yes, it's a cast
Casting int to Choice
Thanks much!
welp, i'm out of debugging steps i can think of, sorry.
I've been out of the programming world for more than a few years and sometimes silly stuff like this comes up and I'm like oh duh
Like riding a bike with words
why does unity not let me referance a script in a prefab?
can you be more specific
If you mean referencing a scene object from a prefab, it's because that scene object only exists while that scene is loaded, but the prefab can be anywhere
I want to make a list of cords of gameobjects but instead of each prefab thats spawns having the same list i want a gameobject that just holds the list in its own script and then all spawned gameobjects with the first script can talk with that script to get info or write info to that 1 list
instead of each prefab thats spawns having the same list
they don't, do they..?
wonderful
I have a script that checks the surrounding cords -1,0,-1 to 1,0,1 and uses bool isBlocked = Physics.CheckBox(spawnPos, halfExtents, Quaternion.identity, layerMask); and then if false is returned it spawns a prefab at the cords but even though there is nothing at the cords its always blocked by the object running the script.
if anyone can help I can share full script
if you want to exclude your own collider you can use a layermask
it already uses a special layermask for the objects to prevent overlapping with other objects
can you explain please what you mean by its always blocked by the object running the script.
if you have a grid system you could probably just store the grid?
its a simple world gen system that has 1 starter block thats 1x1x1 at 0,0,0 and its a prefab also so on start it gets the current vector3 position of the object the script is in and + and - to check all areas around it on the x and z axis to see if a new block with the same function can be spawned but each position returns that is was blocked by the original block
void TrySpawnAtPosition(Vector3 spawnPos)
{
int layerMask = LayerMask.GetMask("objects");
bool isBlocked = Physics.CheckBox(spawnPos, halfExtents, Quaternion.identity, layerMask);
if (!isBlocked)
{
spawner(spawnPos);
}
else
{
Debug.Log($"Blocked at {spawnPos}");
}
}
what if instead of int layerMask you did LayerMask layerMask? (I know layermask occupies an int value, but it may help)
Also, You may want to do a breakpoint at the isBlocked line and see if the debug gives info on what is returned
Lastly, can you show the hierarchy of the prefab you DON'T want to block? Does it have children that are perhaps in the 'objects' layer by accident?
Last thought, make sure the checkbox is slightly smaller than the grid area to avoid overlapping into the next grid
i would also highy recommend you assign the layermask via inspector instead what you got there right now.
[SerializeField] LayerMask lm;
void spawner(Vector3 pos)
{
float frequency = 0.3f;
float noiseValue = Mathf.PerlinNoise(pos.x * frequency, pos.z * frequency);
if (noiseValue < 0.3f)
{
Instantiate(water, pos, Quaternion.identity);
}
else
{
Instantiate(grass, pos, Quaternion.identity);
}
}
new prefabs are not children of the old
yeah you instantiated without specifying a parent so there's no parent
i changed the he to 0.2f instead of 0.5f and now it works but is very hard on the pc
ill remember to use this in the future projects
Couldn’t find anywhere better to post in
go to buildapc discord
should i be applying time.deltatime to gravity with character controller when it makes jump heights inconsistent which is something i dont want? and is time.deltatime really that necessary when handling movement?
deltatime is necessary for handling time consistently
if it's making something inconsistent, you may be using it wrong
If you're doing movement in Update it's not really possible to have perfect consistency. That's why the physics engine uses a fixed timestep. It should be pretty close though. But if you need perfect consistency you will need to use FixedUpdate and I wouldn't recommend CC.
you were both right i used deltatime twice somewhere bruh but i managed to make jump height consistent till about 0.001 so its alright thanks
Hello! I'm using ecs and for my game, I have a Main scene for main menu and Game scene for the actual game. Game scene has a subscene named Subscene with a Prefab that contains GhostAuthoringComponent. I initially have Game scene unloaded and Main scene loads this scene. When Game scene loads, the Subscene is marked as closed and NumLoadedPrefabs is 0 even though the Prefab looks to be baked. Does anyone know if the subscene being closed is the problem?
how to flip colliders like mirror i have a animation that use flip to change rotation ı want to flip collider too(collider is frame by frame)
there is no flip option
invert the size maybe?
for animatons there is a flip option so i use it but when it comes the colliders i dont know what to do
should i separate the right and left animations and add colliders them?
the problem is i dont want to ruin the script and wanna learn if its possible
Then copy paste the script somewhere as a backup. You could even do that to your entire game project
ty for info,do you have an idea to move colliders with flipped animation?
so my text has this background thing for some reason
i tried like 10 different fonts
and none of them worked
so i made my own font
and that didn't work either
this isn't a code question
alr
so where would i put it
like which channel
#💻┃unity-talk .
n did you try searching Google? Pretty sure I've seen a solution about this before
yeah
i did everything i saw on a forum
Hi guys, I'm a beginner in C# programming, I wanted to know if it's a good idea to study pure C# separately from Unity, since I've been told it's different, I also wanted to know if it's a good idea to study Cybersecurity to protect my game
It's not terribly different. Also unless you're making an online game with a massive network architecture I don't see the point of studying network security. And if you are making a game of that scope, you wouldn't be asking here.
unity uses c#, it is not a different language. it is just an older version along with the unity API.
You dont need to give a single thought about protecting your game for a very long time. You could study cybersecurity all you want but it wont matter if you dont know how to make a game/arent making a competitive online game
my game is offline, and if pure C# isn't that different from Unity's then I will start studying C# on my own, because I've been having trouble understanding certain things that seem easy, but since I'm not yet very familiar with Unity I end up not understanding C# very well, thank you for your time
I understand, I was somewhat worried about having to learn cybersecurity because I was told it's useful to protect the game from attacks, but I thought I needed it even for offline games, thank you for the help.
Hi there, i am kinda new, i don't know if this is the correct chat to send my problem, but i have this problem with game objects, i don't really know what this is and if is with gameobjects, or light graphics or something, and sometimes it happends in game and sometimes in the editor, if anyone knows whats the cause for this i appreciate the help ( see the final part of the video)
Possibly an issue with your GPU or drivers.
Are there any errors/warnings in the unity console log?
hi guys, does anyone has experience using XR simulator in Unity? im new to all of this and i'm having some trouble with a project that uses the XR Interaction Toolkit . Could really use some help, Thanks in advance!
hey for jumping what should be the best aproach, using linearVelocity or Addforce? a video speaking about enchancing the gameplay said addforce, but it makes my movement feel weird, but it may just be i coded it wrong
both can achieve the same thing. In most cases you'd want to either completely control the rb through its linear velocity or through addForce
but i mean, wich is better?
i used addforce and linearvelocity for the side movement, addforce felt better, yet for up movement im not sure
neither is better, they both can do the exact same thing. If you're getting different results with them, then you're likely using one wrong
oh, i didnt knew that, thanks
is there a mistake in the way iam calling botAI = gameObject.AddComponent<Bot AI2>(); in this code?
private void Awake()
{
Instance = this;
Text modeStatusText = GameObject.FindWithTag("AIText").GetComponent<Text>();
botAI = gameObject.AddComponent<BotAI2>();
print("start");
// Store the camera's default state when the game starts
if (Camera.main != null)
{
if (originalCameraPosition == null)
{
originalCameraPosition = Camera.main.transform.position;
}
if (originalCameraRotation == null)
{
originalCameraRotation = Camera.main.transform.rotation;
}
}
uiManager = FindObjectOfType<UIController>();
}
the way i have it set up in my hiearchy is that the object this code is in spawns at the start of the game. There is a BotAI2 in the hiearchy as a component of another object.
it was working unitil a second ago, iam not sure if i made a change here or eleswhere
<@&502884371011731486>
!softban 1389566191286353933 bot spam
markbrian0676 was softbanned.
botAI is of type BotAI2, right?
And how (specifically) is it not working now? Any error messages?
iam just calling it botAI but there is only one file called BotAI2, the error iam getting is later on NullReferenceException: Object reference not set to an instance of an object Game+<AITurnCoroutine>d__56.MoveNext () (at Assets/Assests/Scripts/Game.cs:634)
which corresponds here
private IEnumerator AITurnCoroutine()
{
yield return new WaitForSeconds(0.5f);
botAI.MakeBestMove();
}
the main thing is that its supposed to add the BotAI2 when it the object Game.cs is in spawns so that the bot can play against you
Is the object with BotAI2 attached instantiated before this object? if not, then of course it would be null in awake
Wait... misread
the object which has BotAI2 is already on the scene
I ran this and got nothing printed
botAI = gameObject.AddComponent<BotAI2>();
if (botAI == null)
{
print("null bot ai");
}
Then I am confused, you are ADDING BotAI2 there
yes iam adding it to a different object than the one its already in the scene with. so 2 object would have the same script, one started with it another got it after spawning
What line is Game.cs:634
private IEnumerator AITurnCoroutine()
{
yield return new WaitForSeconds(0.5f);
botAI.MakeBestMove();
}
I assume it is botAI.MakeBestMove();
Can you show the rest of the error stack?
If there is more
NullReferenceException: Object reference not set to an instance of an object
Game+<AITurnCoroutine>d__56.MoveNext () (at Assets/Assests/Scripts/Game.cs:638)
UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <2c271b216ff84328b73d1d7f2333e7ab>:0)
i added a print line to debug thats why the position changed
Ok, is the awake from here #💻┃code-beginner message in the Game script?
yes
Do you know how to use breakpoints? I would put a breakpoint on the error line
i think i know how to set one up but not to much on how to use it
Because it seems like something is removing the reference between awake and this line running
When it hits the breakpoint, you can hover over your code and see the values there
put it on line 638?
Yeah
SOMETHING is doing botAi = somewhere else, is my assumption, and that is setting it null
Or perhaps there is a second object with the Game script, which is having issues (perhaps due to being a singleton pattern?)
Ok yeah, something is setting it after Awake.
botAi is what would be null (and should be checked). BotAI2 is a type
would it matter that non of the prints are being set off here?
public void Awake()
{
Instance = this;
Text modeStatusText = GameObject.FindWithTag("AIText").GetComponent<Text>();
botAI = gameObject.AddComponent<BotAI2>();
if (botAI == null)
{
print("null bot ai");
}
else
{
print("wtf");
}
print("start");
// Store the camera's default state when the game starts
if (Camera.main != null)
{
if (originalCameraPosition == null)
{
originalCameraPosition = Camera.main.transform.position;
}
if (originalCameraRotation == null)
{
originalCameraRotation = Camera.main.transform.rotation;
}
}
uiManager = FindObjectOfType<UIController>();
}
Not even start?
yeah sorry thats what i mean
nope, not a single one gets set off
Alright! Then Game is not running
is it on an object when the game starts?
welcome back lol
Hey bro! haha
This is kinda stupid to ask, but is there any noticeable difference between using "else" here or not? Should I try to avoid the else on these types of "return" methods?
which is weird because other functions in the script are being used fine
I prefer the way you have it. It shouldn't be any different
I usually dont. there is no difference though if you're going to do return like that
Can you show the object with Game attached in Unity? Perhaps it is deactivated?
Only Awake, Start, Update (and other unity methods) won't run when deactivated
Other methods will still work
its a prefab that gets spawned in. but looking at it, its deactivated on the object after it spawns
Make sure the tickbox is active on the prefab
Oki doki, I just thought that maybe the else implied some kind of addiotional logic on the if loop or something lol
it is on the prefab
let me see if when i play in the online mode the script is also deactivated
its preference at that point..and if statements are not loops lol
Also check the code where it is spawned in. However, if it is deactivated there, it SHOULD still run awake... not sure
Gtg, bedtime for my daughter. I'll check back in a couple hours though. Best of luck! You're on the right track for figuring out the issue. The line of code itself looks fine.
Alright, thanks for the help!
I was able to fix it by adding this gameInstance.GetComponent<Game>().AttachBotAI2(); to another script, and in Game making a function AttachBotAI2 where i just attach it
<@&502884371011731486>
!softban 1263132919463936032 bot spam
salah_dka was softbanned.
Im new to unity anyone one know the best way to learn c# coding and unity
There are resources pinned to this channel
Can I build a compute shader library or something? I don't wanna have to copy and paste all my funcs every time I make a new compute shader
Is there a way to force unity editor to serialize a tuple?
Why not just make a class or struct?
It aint a problem until I have like 20 structs, but still thanks
No thanks, I actually go outside
so i was messing around with directional lightings, and i ran into some issue where can i ask for help?
hi everyone, i was try to make a simple little UI wiht textmesh pro but this happened...
i did import TMP basics and even extras
the error still stuck even after i deleted the text and canvas
#1390346776804069396 I suppose?
ah perfect thanks
guys is there anyway to stop unity from compiling everthing like when i do a comments it compile and its litrly annoying
yes, turn off auto refresh in the asset pipeline settings
but then you have to manually refresh
Also, I was wondering if I could get some opinions on my current approach to my game:
-
I was thinking of having the timeline controlled by coroutines in a script, where it switches between the two depending on whether an input has been done by the player.
-
Using async/await for switching the animations.
All I was thinking of doing with async/await, was to react to unity event and ensure that the correct animation state is playing during the game. I have everything else pretty much done with coroutines - progress bars, dialogue option select (although I was thinking of doing this with async as well).
Considering all I am doing with async is this, and I can do it with coroutines anyway, am I better off for just getting it sorted with coroutines first, then if I can see if I can refactor it with async/await?
It's for a uni dissertation on a conversion course masters for context, I know my supervisor stresses MVP but polish surely helps right?
Sure, you can turn off auto refresh (Preferences -> Asset Pipeline -> Auto Refresh), but that requires you to manually refresh (Ctrl + R). Personally I would keep it enabled (because if you change something and want to see that change you have to refresh anyways) and just not switch between the IDE and Unity every 3 seconds, but it's up to your preferences
Async functions can replace coroutines and should if you want to await other async things. Make sure to use Awaitable or UniTask (third party) instead of Task.
You do have to think about cancellation though yourself
That's one of the things I'm trying to wrap my head around yeah, like how do the cancellations tokens work, like I get that you initialise them globally but do you then access it in separate async functions, to stop awaiting on tasks once they're finished?
Pretty much all I would want to await for is changing to the appropriate animation and when there is a dialogue option menu, wait until the player has selected an option. Then once again change the state on the animator, if that makes sense.
Like I imagine how you could do this with just coroutines, but trying to wrap my head around it for async
A cancellation token source produces tokens. The tokens are structs and link to the token source. Once the token source is cancelled, the tokens will report this too.
You check the token for cancellation in your async code to stop execution. UniTask Delay functions can take a token arg to stop early for example
I really appreciate the feedback btw, I'm just a little confused.
You can also use Task completion source to be able to await something like a button press. Unitask has their own version of this
So is task completion source like WaitUntil() in coroutines then?
I can give examples of these things if that helps, I use async and these things very often
await UniTask.WaitUntil(() => myFlag);
this will check the delegate each update and not complete until it returns true
Oh sick so it's kinda like coroutines but instead of frame-by-frame it's more state based?
UniTaskCompletionSource completionSource = new();
button.onClick.AddListener(() => completionSource.TrySetResult());
await completionSource.Task;
This will await the button press event without checking some value each update/fixed update.
No, WaitUntil is just the same as doing:
while(!myFlag)
{
yield return null;
}
or
while(!myFlag)
{
await UniTask.Yield();
}
These are not ideal as they are "checking" some state all the time which is wasteful
you can read the task completion source docs to learn more: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.taskcompletionsource-1?view=net-9.0
Ah ok, sorry I'm just having trouble wrapping my head around it.
It is a bit confusing. async Task/UniTask/Awaitable represent some thing that will complete at some later point in time
//Make new completion source
UniTaskCompletionSource completionSource = new();
//Subscribe to our button click event so it can "complete" the task when clicked
button.onClick.AddListener(() => completionSource.TrySetResult());
//Await the button click via the task in the completion source
await completionSource.Task;
Debug.Log("Button has been clicked!");
Perhaps we should move to a thread in #1390346827005431951 to discuss further
Yeah probably, thanks so much though
@daring sentinel I forgot I had written a demo with UniTask that shows how cancellation tokens can be used: https://gist.github.com/rob5300/5b449ee3c35795d2b8dc10261e285f7c
Oh cool, thanks man, just making a thread now if it's cool.
am i just dumb rn? i have a prefab with a camera on it, and a script on another gameobject, i want to attach the camera to the script but when i put the prefab in the hierachy and drag the camera from there and then delete it from the hierachy again the camera gets removed from the cameramanager aswell. is there any solution for that?
i cant have 2 inspectors, can i?
when i lock the inspector from the gamemanager i cant drag that script on that element
do i need to hardcode it so the camera gets attached by script?
I'm really struggling with this localization stuff.
I've had things working in the editor for awhile but now when I'm trying to build it, I'm not getting any of the translations.
I've been messing around with the AddressableGroups because things were faded and I thought maybe they were getting stripped out.
I've created a new group for my localization tables, but if I move the locales there the project can't find them and I get NULL locale errors., and if I leave them as default they're grey and I assume they're getting stripped out on build.
I've already deleted all addressables, Library cache recreated everything and still can't get it to work....
Any advice would be appreciated.
Greyed out? You mean sub assets like when you make a folder addressable? Those are fine
well yea, obviously?
if you set a reference to an object and then delete the referenced object, the reference dies too
Yeah like this
Is the group set to be included in builds? Ask further addressable questions in #📦┃addressables
I would suggest you make the camera that is now part of a prefab- it's OWN prefab. then you can add it to either; the prefab with the camera on it, and/OR the scene object you were dragging it to.
thanks. i got it working now
!collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
please remove your post
Anyone got experience making offscreen enemy indicators
still Don't Ask To Ask
don't crosspost, you were already told to just ask
Has anybody ever heard of an issue where the collision will slowly sink away then be there when the enemy moves? Im using the FPS template and the aimer and the projectiles dont hit after some time. But I can use the aimer to watch the collision slowly sink. I know the collider component is still in place. Its a very strange bug I cant find.
the collision sinking?
In the 12 years i've been using Unity I have never seen anything like this. It's blowing my mind.
a collision is an event that happens at a specific point in time, it can't really change position over time
Unless the values are exceeding floating point precision
I know. But it is. Something strange is happening.
collision sinking sounds really weird
provide actual details about what is happening
for the spherecast documentation
do I select the stuff I want to ignore, or the stuff I DONT want to ignore?
like check the ones I want to ignore, or check the ones I dont want to ignore?
Read the text
you select the ones you want to hit
on/off switch innit
its a bit weirdly worded
yeah, but I thought maybe it works like, check the ones you want to ignore
uncheck the ones you want to check
masks are typically always the filter of what to keep - especially in this case, where the underlying implementation is a bitmask
also wtf
that lets you get the reference of the thing you hit
- Collision there. (red reticle) Capsule in place. 2 Collision gone (white reticle) Capsule still in place. You can follow it with the reticle downward and it will turn red, white until is disappears under the ground.
But the capsule always remains in place.
public static bool SphereCast(Vector3 origin, float radius, Vector3 direction, out RaycastHit hitInfo, float maxDistance?, int layerMask?, QueryTriggerInteraction queryTriggerInteraction?);
public static bool SphereCast(Ray ray, float radius, float maxDistance?, int layerMask?, QueryTriggerInteraction queryTriggerInteraction?);
public static bool SphereCast(Ray ray, float radius, out RaycastHit hitInfo, float maxDistance?, int layerMask?, QueryTriggerInteraction queryTriggerInteraction?);
```there's 1 signature without an `out`, you can use that one
but you need a ray
if you want to ignore the hitInfo, you can use a discard, out _
that works, ill just build a quick ray ig
so it's not actually a collision, but what, a raycast?
Log what you're hitting. the object name
have you tried debugging the raycast to see if it's going where it should?
The drawline is always in place.
why not raycast with a layermask and not have to check for a Health at all
Ray ray = new Ray(legPos.transform.position, Vector3.down);
grounded = Physics.SphereCast(ray, 1f, 1, groundMask);```
appareantly this doesnt work
define "doesn't work"
it turns grounded true for one frame when I land
never after that
legpos is a transform positioned at the leg of the character
overall i dont get why I need a direction, a radius, and a max distance for a fucking sphere
This is Unitys code
when you land you might be slightly clipping into the ground, making you slightly closer to the ground than when standing on the ground
try debugging to check if your sphere is actually reaching
because it's a sphere cast
it's shooting a sphere in a direction and seeing what it hits
ig i should be using an overlapsphere?
well i want to check if im on the ground or not
doesn't that come with a grounded thing?
yes indeed
provided there's gravity
but it has weird behaviour
it checks if the controller collided on the ground every time you call move
which for some reason just makes it turn on and off randomly
even if you are completely idle
BTW
technically theres no gravity when im using root motion
so i cant really use that implementation
rip
grounded = Physics.OverlapSphere(legPos.position, .2f, groundMask).Count() > 0;
eh, this works
you should probably use the nonalloc version if you're going to be doing this frequently just to check for the ground
Same result.
id need to allocate memory for the collider array somewhere else then
also now comes the hard part
making it so I can move in the air
yeah, but you only really need a 1-element array
I want to use a different type of movement for being in the air
....which I already have
but it jitters really hard and turns off gravity in the air
oh shit i figured it out
this is what was happening lol
i was overriding it with root motion by accident
i just made it... not do that
also @naive pawn uve been a huge help. again. thank you so much!
for some reason my OnMouseDown function is not working
Use !code please.
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
oh sorry
using UnityEngine;
public class Gem : MonoBehaviour
{
//[HideInInspector]
public Vector2Int posIndex;
//[HideInInspector]
public Board board;
private Vector2 firstTouchPos;
private Vector2 finalTouchPos;
private bool mousePressed;
private float swipeAngle;
private Gem otherGem;
void Start()
{
}
void Update()
{
if (mousePressed && Input.GetMouseButtonUp(0))
{
mousePressed = false;
finalTouchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CalculateAngle();
}
}
public void SetupGem(Vector2Int pos, Board board)
{
posIndex = pos;
this.board = board;
}
private void OnMouseDown()
{
firstTouchPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Debug.Log("Mouse Down at: " + firstTouchPos);
mousePressed = true;
}
private void CalculateAngle()
{
Vector2 swipeDirection = finalTouchPos - firstTouchPos;
swipeAngle = Mathf.Atan2(swipeDirection.y, swipeDirection.x) * 180 / Mathf.PI; // Convert radians to degrees
Debug.Log("Swipe Angle: " + swipeAngle);
if(Vector3.Distance(firstTouchPos, finalTouchPos) > 0.5f)
{
MovePieces();
}
}
private void MovePieces()
{
if (swipeAngle < 45 && swipeAngle > -45)
{
otherGem = board.allGems[posIndex.x + 1, posIndex.y];
otherGem.posIndex.x--;
posIndex.x++;
}
}
}
does your gameObject have a collideR?
so you can´t see the "Mouse Down at:" message right
no
Debug.Log("Mouse on : " + name);
I added this line now
I'm pressing on the Game window
but nothing is showing in console
could be that another collider is blocking your objects
can i post in here if the scripts are quite long or should I do it another way?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/
📃 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.
ty 🙂
how so?
I found it. Its the rigidbody. Removed it and its all okay now. No more sinking.
only the gem has a collider
then i am out of ideas mate.
is it a problem with Unity 6 or something?
nope surely not
So I have an issue that I've been trying to solve for a few days.
My player has unity's built in character controller component and I'm using this script to handle player movement etc.. https://paste.mod.gg/ogxykbvdijxq/1 I'm happy with how this is all working
I also have a robot that floats around the player when stationary, and follows the player when moving. This is the player follow script https://paste.mod.gg/ogxykbvdijxq/0 this is also working fine
The issue I'm having is getting the floating robot to have proper collisions with the walls and floor etc.. of my map. The map is made up of modular pieces with mesh colliders.
I understand it wont work because of no collider and rigid body, so I have tried to add those components and change the script, and I've had (very little) success. I can get the robot to follow like this but it only will once the player stops moving, and even then it moves incredibly slowly (1 unit a second ish) I know it's because of how these 2 scripts inherantly interact with each other, but I'm scared of breaking what I've got so far. Can anyone help please?
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
I fixed it apparently it was in unity 6.2 for the input handling system it's set as new Inpt system, and it doesn't support OnMouseDown
Thank you for your help <3
Does anybody have any advice on getting better at coding cause I feel when I watch tutorials I don't actually learn much and feel more like I'm copying the tutorial and not learning
Do a tutorial and follow along. Then try to redo the SAME project from what you remember, without following along. Then try to add a single SMALL feature to it. Repeat
I also recommend making small projects for single ideas, like making a bouncy movement script, and making a cannon, things like that
K so like if it shows me how to make a game where you collect coins do it then do it myself but add parkour or something
Parkour is kind of a large and involved feature, so I would start smaller. Like make an explosion happen when you collect a coin, or an animation
K I get you
Also you know how sometimes in script a word has a capital in it but others don't what's the reason why
That is just to help your recognize how a type or variable is set up. Often people do capitals for public variables and lowercase for private. There are many conventions (for example, some do an underscore for private variables _myInt), it's just important that you keep things consistent.
Here is what microsoft recommends:
https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/identifier-names
So it sorta doesn't matter as long as you don't do it randomly
Basically. But I would find an actual convention and use that. That way it will be easier for if you want help. Just don't go TOO random I mean.
K thanks for the help
What is the best option to learn C# Unity?
see pinned resources and !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
if i use the ECS package that Unity has, is there anything special i have to do other than setting up my actual Data and Methods for it?
If you use ECS you have to build the whole game with systems, entities, and components
why is the remove component button at the very bottom instead of where it should normally be?
it's in its normal position with different components
actually, this seems to be the case with light components only. any ideas why this is?
yeah that's fine but there's nothing special other than that right? Like the frame of the ECS is there i just gatta fill up the "buckets" so to speak?
I'm honestly not really sure what you're asking
So i was like making an ECS already then I found out that Unity has an ECS package
they uses interfaces to turn the structs into components and i didn't know any of that part of it i was simply on like stage 1, learn programming and learn ecs stuff
so i just wanna make sure that when i start working with the unity stuff there isn't some other details i need to know about... also i never knew programming could be so fun like this either....
ive learned so much and actually sat for like 16 to 20 hours a day over the past 4 or 5 days just talking to AI and learning the general fundamentals of the stuff or w/e... and it's honestly been way more fun learning programming this way and the introduction to Methods has been way simpler, I know C# is nicer than C++ and C or w/e but im telling yah like CS50 making you do the Mario double pyramid didn't teach me anything
When i first started learning they made everything so sound so complex bro and then i watched a video and talked to chatGPT a bit about stuff... then i just started plugging away with IDs and Tags literally turning my wannabe-game design notes into actual data by just creating lists
There's so much more and I have like 8 notepad++ docs where i keep going through the learning process and organizing my Data, renaming the conventions, all these different things ooh oohh... like so much more... Oohh Oohh i learned about the Namespacing convention not because I needed a header file which i will need... but because I wanted to make my Data calls simpler like... Im taking a break though for today because over the next few days is going to be more learning and i really really really wanna have my IDs and Tags organized and set in their own Namespaces or w/e
as a meme i made a joke i was gunna call the game "War of the Enumerators"
I want to get the current Scene of my game using scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene().buildIndex; where scene is an int. I have this line of code in update but when i run the game, scene isnt being assigned a value
My game is at scene number 3 (based on build)
but the variable scene displays 0
Debug.Log is your friend
log which scene is active, log the build Index etc.
If that code is actually running, the variable is definitely being assigned