#💻┃code-beginner
1 messages · Page 801 of 1
How does the ground check work? You already have to check if the player is touching a planet, the same method can also tell which planet it is
Hey everyone, I was just wondering if there were any people that had any experience with the experimental Unity Graph Toolkit. Any help at all would be great!
If you have a question just ask it in #↕️┃editor-extensions
Got something that's driving me absolutely nuts.
IEnumerator TestCoroutine()
{
while (true)
{
Debug.Log("Running1");
yield return new WaitForEndOfFrame();
}
}```
If I call this from my monobehaviour's start method, it runs fine. As soon as I call this from another object, it stops after a single loop:
```c#
public void Flash(int newIterations = 0)
{
StartCoroutine(TestCoroutine());
}
Any ideas at all?
Does the other object get destroyed or disabled
No
What's more, if I have one instance of the coroutine running from start (runs fine) as soon as I try to run the coroutine again from this other object, both stop
I've checked. There's no StopAllCoroutines() or anything similar in play. in theory it should run forever
Ah, nvm. I think I've found it. The same event that was causing the external call of the coroutine was also (elsewhere in the code) for less than a frame disabling the gameobject with the coroutine on
I didn't pick up on it because it was enabled again immediately afterwards. Silly me!
anyone here used Steamworks.NET before? I was wondering if there is a way to get a ping value between player and host somehow, but I'm not doing any actual multiplayer yet, just lobbies
chatgpt said that I could technically do a round trip with metadata callbacks, but apparently its unreliable/hacky
I'm assuming ping is more for when I have actual multiplayer in place?
(like NGO)
Ping between player and host would have to do with your actual multiplayer networking framework, not Steamworks
Steamworks is just a steam API Library
so if I wanted to show ping in the lobby, the server would already need to be running at the lobby stage right?
any problem with that approach?
I like the ping display aesthetically, but it's not that important I guess
Hello guys, I am new at using C#. I am not sure how to deal with this error which stop me from running the game
🤦♂️
your VScode doesn't look configured .. get it setup so it auto completes for you and underlines errors
!vscode
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
Thank you, such a life saver
btw, if you want to wait a frame you'd want yield return null;, not WaitForEndOfFrame
Oh ok, thanks!
I'm new to game development and I have 0 experience with unity just started to learn game development with unity after 1 week of exploring unity i didn't get any progress can anyone help me to provide best resources to learn unity studio I'm very passionate about game development btw I'm a computer science second year student and I'm good at DSA, MERN stack, problem solving, coding fundamentals and I'm also goot at programming languages like c++, javascript please give me best resource to learn unity i want to starting from absolute beginning if anyone wants to help me then message me personally.
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
hey, quick question, I have to make consumable items (with different rarities) and despite doing some researches I'm still not confident enough to go at it so instead of asking chatgpt, I'd love to have an idea of how you guys would do it. Thanks !!
not easy to answer such an Open question
how could I help narrowing it ?
every project, has requirement with different solutions
well it's a party game with items you can use when it's your turn
each has a rarity and an effect
imo its more about you should try something, then realize where its not working how you want and keep iterating until you find something that works
that can still mean different things / function specific ways
the usual contenders, individual components, Poco (normal classes), Scriptable Objects, or a combination of these
not understanding makes me feel a bit bad
like what exactly?
don't overcomplicate the system, start small and build up.
are they timed consumables? do you know how to make a timer? etc.
you have them in your inventory, when you use them they disappear and their effect apply, but yeah i can't do a timer
i was originally thinking about OOP but i feel like this would be a hastle
I mean everything you do is still OOP.
C# is an oop language
I think i will try to just make a prefab with a linked script
You mean like polymorphism maybe
You can do like a base Consumable, then each one that inherits it has its own special logic for how it should affect the consumer
blabla person(name, age)
{
person.name = name;
person.age = age;
]
I only use that in python 4 years ago so i'm not entirely sure
if you're entirely new to C# & Unity maybe overtaking a consumable / inventory system might be a difficult uphill to start on
well the other thing i could do now is multiplayer, and having already tried once it scares me
multiplayer is pretty complex, its like relearning everything from scratch
is creating a prefab for each item bad ?
not necessarily, it really depends how they will be used.. Will they need to be tangible objects in the world or just code that reacts etc.
well i made one with mirror but then it started breaking because i wanted to make it server authoritative and then i just ffed
Guys how can i fix this, everytime i change a code basically everytime i change something in unity it reloads and it takes about forever. I have to close the unity entirely just to open my project again but it will not have the changes i made
when I first started, this helped me greatly towards it, Is more focused on "abilities" but most of the concepts are similar
https://youtu.be/Jv9jGyIWelU?t=266
Welcome to the Prototype Series - a group of videos that focuses on the creation of playable prototypes, showcasing how multiple features of Unity can be used to achieve game mechanics that can be used in real-world scenarios!
Is there some game mechanic that you would like us to try and prototype? Let us know in the comment section!
Download...
How can i fix this guys
this uses a component approach ^
just code I think
you can maybe close unity and refresh the library
i'll watch it thanks
How can i refresh the library?
delete the folder and open project again
On the project directory, delete the library folder right? Is that it?
yes
its just cache, it gets rebuilt
its gonna open a new untitled scene after, just gotta open old scene again
Ok it's now building, is that the long term fix? May i ask why did it happen in the first place? There is no error in my code
it might, sometimes it helps, sometimes it doesn't. Cache can get corrupt or bad in some cases and cause longer hang but not always
other than that, it also depends on your Specs, how many assets etc.. Errors in code doesn't affect how long
every time you save it has to refresh all the assets
some people turn it off and manually do it, really depends . Its a normal part of using this very outdated backend
was the timestamp a choice ? cause i don't rlly understand where it links to consumables from there
CPU: AMD Ryzen 5
GPU: NVIDIA GEFORCE RTX 3050
RAM: 16GB
This is the specs, is this the culprit?
not necessarily, though for example with a Ryzen 7 might be even better for CPU heavy processes like this.. GPU has no part in this.
I have a M1 and in Unity it flies past my Ryzen7 by a mile
arguably, macos is also heavily optimized compared to Winspy
consumable concept works similar to abilities
i just realized the timestamp you gave is in the middle of the modular system part
you just change a couple of things around
okay yeah I think that's what I'm going to use
- "Ryzen 5" doesn't actually say much about what CPU you actually have, it just gives an indicator as to how many cores. there is 0 info about the generation or speed of the cpu there
- disk speed also plays a large role in things like the issue you are facing. if you are using a HDD rather than a SSD that will impact performance
this was what i meant by OOP
ya mainly to show you the Inheritance can be used for different Abilities/Consumables
so I can't just put that script on my player and that's pretty much his inventory no ?
You can put it on the player if you want, those are details that don't matter much. You're jumping ahead too much
yeah that was stupid as well, my bad
Get a item / consumable working first, where you put it doesn't matter.. It can be a component (goes on a object) or just lives in a item manager itself and only through code
I like to have a clear view of the full thing before starting
understandable, but in most cases if you don't get something going you can't grasp the pros and cons without hitting limits first hand
"I did this way but don't like it because of xyz " now you traveled a path that you know you might not take again or use it for a different thing
well that's what i did with the multiplayer
iteration + experience. it never stops
I lack the vision to make this iteration
is it possible to make a variable that can take any script ?
what would be the type ?
define "Any" script
Hello everyone, I have a prefab which contains an image gameobject with image component. I am getting those via the following line : Transform imageTransform = newItem.transform.Find("Image");
Is this just fine or is there a more efficent way to do it?
use a serialized field rather than Find
well for one item I want one script and for another item I want another script
or rather different functions
just put the type
but isn't the type the name of the function/script ?
the type is the part you define, if you did class ConsumableXYZ you can use ConsumableXYZ as the type
if you did
public class ConsumableBase : MonoBehaviour
then HealthConsumable : ConsumableBase
You can use ConsumableBase or HealthConsumable or even MonoBehaviour but you wont get much. use from that
I know what a serialized field is but I don't know how that applies to : GameObject newItem = Instantiate(itemPrefab, content.transform);
well for starters your prefab will need a component on it to hold that serialized field. then it gets assigned to in the inspector. then instead of using "GameObject" for the prefab type, you use that component so that Instantiate returns the reference to the correct component instead of just a plain GameObject reference.
then it's just a matter of accessing that serialized field (ideally via a property)
Does itemPrefab have the Image component you want, or are you trying to pass an Image component to itemPrefab?
I think I understand, thanks
to expand on it
eg itemPrefab were of type Item
if you want its Image component (assuming you make a public field/property in Item class)
you can do
Item newItem = Instantiate(itemPrefab, content.transform);
newItem.Image.DoStuff ```
itemPrefab currently has two child gameObjects, Image which has the image component and Count which has a textmeshpro
Does the root of itemPrefab have any scripts on it
Not currently.
So you should probably make an Item script, give that script serialized fields for the image and count text, then add it to your prefab, dragging in the things you need into those slots.
Then, you'd change your public GameObject itemPrefab to public Item itemPrefab and spawn in the object with a reference to that script directly. Then you'd just be able to do newItem.image to get its Image child
Ok. That makes sense. But I'm still not sure how newItem.image would be used by the child Image gameobject image component.
why would it be "used by the child Image gameobject image component" (whatever that is supposed to mean)? it will contain a reference to that object so that whatever instantiates the prefab can get that reference
you make a field for it in the Item class
you're linking it there
ok. That makes sense
You want the image component right? The image component isn't using anything
You can do
GameObject newItem = Instantiate(itemPrefab, content.transform);
newItem.GetComponentInChildren<Image>().DoStuff;
``` but that gets very brittle (imagine you want another specific component and 2 of them exist, it will grab the first one not the one you may want)
I'm glad I asked, this is a better approach. Thanks for everyones help help.
Yeah..I'm trying to avoid that kind of stuff
and optimize as much as I can
Ok...this is what I came up with...this is what you guys were suggesting right?
My prefab root object now has InventoryItem script attached to it.
public class InventoryItem : MonoBehaviour
{
public Image image;
public TextMeshProUGUI count;
}
GameObject newItem = Instantiate(itemPrefab, content.transform);
InventoryData data = itemIndex[item.Key];
InventoryItem itemScript = newItem.GetComponent<InventoryItem>();
if (itemScript != null)
{
if (itemScript.image != null)
{
itemScript.image.sprite = Resources.Load<Sprite>(data.image);
}
if (itemScript.count != null)
{
itemScript.count.text = item.Value.ToString();
}
}
if itemPrefab is set as InventoryItem in the inspector, there is no need for this line
InventoryItem itemScript = newItem.GetComponent<InventoryItem>();
again, use the type you actually care about for the prefab, not GameObject and you can skip the GetComponent line
Sorry...this is my first time making a prefab. How do I set the prefab as InventoryItem? I tried removing the InventoryScript component on my Item object (see attached screenshot) and it allowed me to but now it is not allowing me to drag/drop the Image + Count object s to the script.
Shit..this is the serializedfield thing that boxfriend said isn't it
one sec
Put the script on the root object of the prefab
Then, you can make a variable of that script type and drag in the prefab from assets into it
[SerializeField] didn't change anything. It was on the Item object prior
You won't need to do GameObject itemPrefab, you can do InventoryItem itemPrefab
Hmm...I tried that a while ago (and now) and visual studio says "Cannot implicitly convert type 'UnityEngine.GameObject' to 'InventoryItem'"
Well yes
Why are you still trying to store it in a GameObject variable
Use InventoryItem
that's the entire point
you may need to drag in the prefab again after you change prefab from GameObject to InventoryItem
iirc the inspector will say Mismatch type
just to be clear, after you put InventoryItem on the prefab there isn't anything else you need to do in the prefab itself, what type you declare for that prefab where you drag it into is what matter
Yep. That totally worked. I am now accessing the variables directly. Hopefully I got it right this time :
InventoryItem newItem = Instantiate(itemPrefab, content.transform);
InventoryData data = itemIndex[item.Key];
if (newItem != null)
{
if (String.IsNullOrWhiteSpace(data.image) == false)
{
newItem.image.sprite = Resources.Load<Sprite>(data.image);
}
if (item.Value != 0)
{
newItem.count.text = item.Value.ToString();
}
}
that == false could just be a !
also unnecessary if (newItem != null) here
done and done!
stylistic choice - I prefer using == false easier/ quicker to parse for me than a thin !
Thanks a million guys...super helpful...I couldn't do this without help
early return pattern , where my dawgs at
guard clause go brrr
pesky nesting of { }'s 😵💫
InventoryItemUI newItemUI = Instantiate(itemUIPrefab, content.transform);
if (!string.IsNullOrWhiteSpace(data.imagePath))
newItemUI.image.sprite = Resources.Load<Sprite>(data.imagePath);
else
newItemUI.image.sprite = defaultItemSprite;
newItemUI.count.text = item.Value == 0 ? string.Empty : item.Value.ToString();```
Can someone direct me towards a good tutorial for camera? I'm using Cinemachine Third Person Follow camera and that doesn't come with set axis movement, you have to code it yourself
check the unity third person starter assets you can see how they coded it, pretty simple
that , or use a blank project just for that purpose
Yeah that's what I meant
Third Person Controller has a prefab, it has the code to control the third person camera.
I have a snippet of it in my old project if you want to just see the function rq
https://paste.mod.gg/bltktisxnask/0
A tool for sharing your source code with the world!
basically comes down to only rotating a Cinemachine target on the player
Thank you
Hiii, one question:
I have a sprite, and I config it to be the right proportions, but now im doing an animation for the button and the button was like this: (image1)
So I could put that the expanding anchors (or however its called) are in the middle of the black, but now I have the same size box but like these (image 2):
Its a spritesheet, and each one hast the anchor in the white zone, but that does so that it doesnt appear all the way from the right the white part, instead it appears almost filled instantly.
How can I do that the scale make sense here? Idk if i explained, sorry
not sure this is a code question
oh, sorry i didn't see there was another chat
https://puu.sh/KHByl/c4f7d90884.png
I pressed Tab to autofill and it gave me |=
I'm curious as to what this does?
bitwise OR assignment operator
something something turns the bits on without replacing what was there
int a = 1; // 01
int b = 2; // 10
a |= b; // 01 | 10 = 11
a == 3```
i have a question where can i learn coding fast and easy ?
Fast and easy? No clue
fast then ?
I don't think that's how learning works
there are pins in the channel. you likely aren't gonna learn it properly at all if your first goal is "fast and easy"
and let me guess, for free
How fast you learn depends on how much effort you put into it
you have to modify how your brain is wired
start with the basics https://learn.microsoft.com/en-us/shows/csharp-fundamentals-for-absolute-beginners/
🤔 not sure what you mean by this, there are tons of free resources out there for learning that are just better than paid ones anyways lol
i was replying to the dude
im aware, but free doesnt really affect anything here
no it can cost some money
the learn site from microsoft is what you will need tbh
everything else , esp paid is a scam..
- cough * Udemy * cough*
freecodecamp is ok but it just a repost of a microsoft learn site lesson
Start with YouTube if you want to learn coding. Find yourself a lot of tasks to do depending on your skill level. Do them often. Take lots of notes.
If you want to get good at Unity fast, I think Unity Pathways are pretty good. There might be better resources.
Practice daily and you'll be decend within a year
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the learn site is good but for Unity specific..
it won't teach you the basics on c# which you should learn first before touching unity
ok
something like this will show you the absolute basics so you can start to understand what the stuff in unity mean https://learn.microsoft.com/en-us/shows/csharp-fundamentals-for-absolute-beginners/
may i ask why it has to be so fast
is someone chasing you
Extortion is a common one
no im just autistic
Is there a way to achieve this without changing the MySampleFunction's header to match the event's output type? A function appears to show up in Dynamic Parameters only when the two match and I don't want them to match.
make multiple signatures?
Inflexible. I want to pass this torch to the mappers and game designers.
Custom button script
You mean replace the input field with a custom one?
Dont think thats a button.. just a UnityEvent<DamageEvent>
Correct
On a similar note, can stock unity allow something like from the editor ui?
thats tricky.. maybe a custom editor script
if you're working with designers n whatnot depending a lot on inspector work you'd have to get familiar with editor scripting
Enums
Idk
Hey so im trying to make an ability system for my player.
Im unsure of if i should use Scriptable objects or abstract classes
I love the idea of being able to drag and drop abilities into my ability manager and have the behavior change, but im not sure of the best way to run code through scriptable objects.
Meanwhile i could have an abstract class compnet attached to my player for every ability but how would i control them from my ability manager(which handles switching abilities and inputs)
perhaps if you better state your usecase you might get a better solution
At that point just add some code or use visual scripting or some custom solution
You'd need to make functions that themselves have conditions in them. Like a function that exists early unless condition_a, so if that's not true, it'll just skip
I see. This answers my question. Many thanks.
the two arent mutually exclusive btw.. SOs can also be abstract
you can run functions in SOs just like any other class
Unity just makes them Assets / Tangible things in the editor, otherwise they are just like any other classes
I would make a state machine where ability is one of the states, like walking
that is pretty bad to extend on
if you have multiple abilities you're breaking the Finite State concept
SOs are pretty decent in most cases if done correct
I had a few attempts at state machine NPC enemies outside of Unity, and it didn't work out well. And those enemies were pretty basic.
wait wait wait
so im understanding that right
So i make a base "AbilityObject" abstract scriptable object
Then for any ability i make a new "Laserbeam" class that derives from that, so i can inject and overide behavior
Then i guess i would need to create a new asset for it in the editor, drag and drop that into my ability mananer and that would work?
So any new ability would need its own script overideing behavior and a new asset
I have a state machine for my ability slots, so you can only use one at a time and itll activate any ability placed within the slot
the whole point of Finite state is that you're in 1 state at a time, if you have a invincible ability and flying ability, how would you apply both..
In theory, this can be solved by having 2 state machines.
if you want 4-5 abilities active at a time you make multiple statemachines? I don't understand
doesn't seem to scale well
ye
You can combine inheritance with SOs without issue the only difference, yes you need to create an asset per ability class. But the benefit is you can have same ability with different stats
Perhaps we understand the concept of ability in our own way
if you can swap them I say making them objects is far easier without having to change the core enum / state
multiple abilities is what I was talking about, if you are using multiple at once how would FSM work there
What if some abilitys are wildly different from each other
From my ability manager i would imagine i just check what ability is in the ability slot, then i call some "Activate()" function
Whatever is in that slot doesnt matter, it will activate
However what if my abilities need refereneces to something on my player, like the location to fire a projectile from
I would think i could pass that through my "Activate(Transform AttackPos)" but that would mean abilities that dont need that would need to pass that information through anyways?
if its a cast ability lets say, it has an origin you have to pass it.. it doesn't care where you get it from as long as you pass it.. this way it can come from player, npc whatever
this is a really common problem
i tried to tackle this in an RTS I prototyped a while ago
yeah this isn't exactly an easy task and ultimately you need to experiment
I dealt with this particular thing by creating an "ability target" class. You can feed it a variety of things, like a position, a unit, a pair of points (to draw a line), etc.
so maybe even a Setup method per ability and they all make their own version to what they need
You can then ask it for things like "a position" or a "a unit"
so, you'd stuff all of the possible targeting data you can into it, then hand it to the ability
This means you are responsible for putting the right data in
It made it easy to create abilities that can target a unit or a point on the map
ya like if you have a healing Ability, you have a Use(Target t) etc.
If you click a unit, the AbilityTarget class has a reference to that unit
and it uses that unit's position when you ask for a location
if you click the ground, the AbilityTarget just stores a position, and returns that directly
You lose some type safety here
It's possible to pass an invalid AbilityTarget
the ability classes should correctly handle bad target data
e.g. by failing to activate or failing to even accept the command in the first place
Actually, my state machine just had 1 class that stored all the data and links
Okay so that way instead of needing Activate(Transform target)
you Activate(AbilityTarget target)
Which allows you to pass it with much broader information based on the ability?
Yep.
abstract void Use(StatesData data)
conceptually, it's not that far off from just doing Activate(Unit targetUnit, Vector3 targetPos, float florp, ...)
but you can at least bundle everything into a single AbilityTarget that can provide some kinds of targeting data based on other data
(like using a unit's position)
Okay so I just need to make a class that contains can handle any possible information an ability would need. Then i just pass that through as a bundle instead of 1 by 1
because if i Activate(Unit targetUnit, Vector3 targetPos, float florp, ...) then an ability wouldnt work if i didnt have a "targetPos" but i had everything else
This is enlightening
The ability could have a ValidTarget method that tells you if it can use the AbilityTarget object you currently have
You can also further go down the chain like Abilty but also have AbilityType as a enum or maybe just CastAbilityBase etc.
the rabbit hole goes deep..
Let's say there's a poisoned projectile ability.
There should be logic somewhere dealing poison damage over time.
Well, okay, in this particular case it might be worth coding that into a character, but eventually you'll get a wall of text for status effects Team Fortress 2 has. Won't recommend.
ya the ability would handle the "effects" to the target
including the timer
the target should never care about how its health is being affected, just that its being affected
"Effect" systems are another great place to abstract yourself unconscious
yeah, the unit has no business understanding what a poison debuff is
it should know how to take damage
it could ask its debuffs to do things
like give it a tint color
That said, trying to avoid piling up status effects in one place might also be bad design, as you'll then be running around the entire codebase wondering what bug causes damage to be doubled for no apparent reason.
another reason a FSM may not work for this esp if you have multiple/stackable status effects like
you can be both Poisoned and on Fire
yes, these aren't mutually exclusive states
a finite state machine only makes sense if you can only be in one state at a time
I wonder if it'd be a good idea to express would-be state machine states like walking, running, etc as status effects. You don't typically think of "being on fire" and "sprinting" as the same type of concept, but they kinda are.
Actually, TF2 already does this for scoping a sniper rifle and revving-up a minigun, which on the user end is a player action and not a status effect in a conventional sense.
You could only be "Walking" OR "Sprinting" at once, never both.
but you could absolutely be "Sprinting" and "On fire" or "Poisoned" at the same time or even all at once.
Hello, I have been having a real problem with returning projectiles to my pool when the player enters the GameOver state I cant for the life of me get them to just reset without breaking in some fashion.
Its quite a roundabout issue and probably caused by my own spaghetti code because I have a good few functions and classes that interact with or handle projectile logic. I was wondering if anyone would be so kind as to help step through the logic with me as I have been trying to fix this for a week now.
you should probably start by showing the setup and where is it doing what is not supposed to be doing
I typically reset the state when I get it from the pool rather than returning it but not sure if that matter
It'd probably be easier to force individual mutually exclusive status effects within a larger status effect system over making a system of mutually exclusive states in addition to the status effect system you'd need anyway.
Alternative way to look at it is that you walk under the status effect of sprinting, rather than sprinting being its own action.
I can try and share all the relevant logic the problem is I dont actually have any errors that appear so Im not so sure what is causing my issue, I think its probably an execution order issue? Not super sure though
!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.
yeah but not clear wat exactly is breaking or what the issue is
e player enters the GameOver state I cant for the life of me get them to just reset without breaking in some fashion.
breaking is pretty vague
state machines can get really annoying to think about
e.g. imagine you can grab an enemy, and the enemy has an ability they can use both when grabbed and not grabbed
do you have a separate state for that ability when they're grabbed? do you just have multiple transitions out of the ability state?
You're right my bad. The first thing I tried was to stop all coroutines running on the projectile, reset it how I normally do (which was working until I added a return all active function) The projectiles would sometimes come back without reset rotations or positions etc.
Then I tried simply turning off any visible elements of the projectile (they come with warnings and indicators) and doing so sometimes the projectile remains active (although invisible) and isnt put back into the pool
(the latter means you need MANY transitions if there are many situations the ability can be used in)
equipping the state machine with a state stack sounds like it'd help – some states would simply pop the stack when they want to end
but what if the enemy gets grabbed while using the ability?
have you tried doing what I do ? instead of resetting something on return to pool, just let it diactivate the gameobject as normal (that lets all routines stop n all)
then when you request from pool is when you reset their position/ rotation to what you need it to be on spawn
basically almost like you're running your own Awake() version on Get
In the most literal sense of just projectile.gameObject.SetActive(false);?
that in the Release function yea
I have not, I will give it a try thankyou for the suggestion I hadnt considered that was an option until now
I can show you how I do my arrows rq if it helps
I would be silly to say no to that opportunity xD
Is there a way to execute a script graph from a unityevent panel?
arrow mainArrow = null;
if (usePooling)
{
mainArrow = arrowsPool.ObjectPool.Get();
}
else
{
mainArrow = Instantiate(arrowPrefab);
}
mainArrow.Init(firepoint.position, firepoint.rotation, usePooling);
mainArrow.SetDamageAmount(weaponStats.damagePerArrow);
mainArrow.LaunchImpulse(Stats.ArrowSpeed * firepoint.right);
OnArrowLaunched?.Invoke(mainArrow);
arrowsFired++;```
public class ArrowsPooling : ObjectPooling<arrow>
{
}
//arrow
private void OnEnable()
{
deactivatingRoutine = null;
}
public void Init(Vector3 pos, Quaternion rot, bool pooling = false)
{
usingPool = pooling;
AssignNewVals();
transform.SetPositionAndRotation(pos, rot);
}
public void AssignNewVals()
{
rb.transform.SetParent(null);
SetNewLayer(projectileLayer);
rb.isKinematic = false;
col.enabled = true;
hasHit = false;
rb.linearVelocity = Vector2.zero;
rb.angularVelocity = 0;
SetGravityScale(gravityScale);
deactivating = false;
}```
Ahhh very clever, I like the fact you've given yourself the option to use a pool or instantiate them, im also happy to see that your logic is already fairly similar to mine so I guess im on the right track. I will try it this was and pray that helps
hard to see on Gif but can spam many arrows without a nudge in computing
Guys I am new to making things on unity or at all! When I am trying to make a 2D cultivation game for mobile. Like I wanted to be able to be bought or downloaded in the App Store for everybody. When I first opened it I had this error message and I don’t know how to fix it.
Seems lovely and responsive too, awesome
relog helps
try sign out and sign in hub
How 😭
Problem: even though I wrote that normal button color must be the test color (red), it appears transparent when I don't interact. But only when I hover or click, I can see the transition from red to the highlight/hover color.
I've tried applying the test color to the Image color, but it didn't help.
How do I make it so, normal color is the testColor, and not transparent?
Hmm okay
Like this is my first time downloading unity and I first opened a 2-D one and it just popped up that
Welcome to Unity
☠️
yeah that is a bug but i think it only appears once
How do I fix it?
how did you set theme.testcolor
I am signing back in hold on
Yay it’s gone I think
thank god
Real
you found the button
Now…. Got to find out how to make an idle cultivation game…
It had 0 on A channel (I've set it as transparent). Sometimes I wonder I might have an extra chromosome.
lol was just about to say to check that but yeah at least you caught it 👍
I'm really confused - what is it upset about here? I'm doing the exact same thing elsewhere
you're calling the function rather than subscribing it
oh wait is it the true/false thing
the correct syntax would be:
LobbyManager.OnLobbyJoined += ToggleLobbyUI;```
but since it's a System.Action with no parameters,
you would need either a lambda here
or a wrapper
(or () => ToggleLobbyUI(true);)
isn't it impossible to unsubscribe if I use a lambda though?
or did I misunderstand that part
basically yes unless you keep a ref to it
like:
void EnableLobbyUI() {
ToggleLobbyUI(true);
}
LobbyManager.OnLobbyJoined += EnableLobbyUI;```
not impossible you just need to keep a reference to it in a variable
you can use a wrapper function like i showed though
to make it simple
that's probably the simplest thing I could do yeah
wait how do you keep a reference to a lambda?
in a variablke
I knew that much lol I mean like what type?
Action myDelegate = () => ToggleLobbyUI(true);```
Whatever delegate type the lambda conforms to
in this case System.Action is what you want
I'm honestly way too tired to understand that today I think lol
Delegates are just variables that hold functions. A lambda is just a function you define inline
when we sub and unsub with a member function its easy
otherwise yea we have to manage keeping a ref to the "anonymous function" used
so a delegate variable can hold any kind of function - a regular one or a lambda
and yeah by keeping a reference to it, you basically make it not anonymous anymore
but I thought Actions are events - how are we storing a function here?
Action is a delegate type
They are and always have been variables that store functions
The event keyword simply adds rules to a delegate type field so it can be used for events
You can but its a bad idea because you can accidently assign instead of += and fuck it
I was wondering what that did lol
also events can only be invoked in their owning type
When you do myEvent += MyFunction; you are just storing your function as part of the delegate
it actually takes any existing function in the delegate, "appends" this new function, and stores the collection of all the functions added to it in the delegate
so when you do myEvent(); it just calls all the stored functions
so yes - events and delegates just store functions to be called later
ahh ok
events really seemed like magic but your explanation makes sense as to how something knows what is subscribed
Fancy list of functions to call when event goes off
be glad its not cpp where we need a special std lib type to get the ability to store functions with captures easily
https://en.cppreference.com/w/cpp/utility/functional/function.html
c# lambdas make it easy
Btw delegates (events) can make memory leaks
Oh yea, an event sub is a reference and thus prevents GC unless both sides can be deleted
And if you forget to unsub with something you destroy in unity then that can cause issues
OnLobbyJoined etc are all expecting a function. When you call a function, you get it's return type, in this case, void. void is not a function.
😴
yeah that's why I asked about the lambda because I tried to subscribe/unsubscribe with discards before 😭
not quite – this situation is fine:
publisher.AddListener(subscriber);
publisher = null;
Assuming no other references to publisher exist, the GC will prune it
subscriber has no reference to the object formerly referenced by publisher
Ah, scrolled. Already answered, and better
yes if we explicitly clear the event/whatever that works too but no point of its owner is going to be destroyed
now, assuming publisher is kept alive, then the object referenced by subscriber will stay alive too
this is less of a memory leak and more of just...an error
if subscriber is part of some Unity object and you've destroyed it, you probably do not intend for it publisher to be trying to call it at all
why cant unity just delete managed objects smh /s
Hi, I tried cobbling together a dialogue script for my game and got whatever this mess is. I used to have it so clicking the button to increase the talkcount would have its own switchcase in the talking function, but that seems way too complicated and only works if I want one extra dialogue, another would need another switch case and so on so thats out of the picture. Currently with this snippit of the script that I'm actively trying to work on, the text will always be 'Hey.' no matter what the talkcount is, and when I walk away and come back, clicking the button to increase the talkcount will make it add another number on TOP of that, so at first it adds up in 1s, then 2s, then 3s and so on. This is my first time working with switch cases and dialogue as a whole so I have basically no idea what I'm doing lol, am I missing anything important that I just don't know about?
{
if (touching && Input.GetKeyDown(KeyCode.E))
{
switch (gameObject.name)
{
case "kelpy":
if (talkcount == 0)
{
talktext.text = "Hey.";
option1.onClick.AddListener(delegate { talking("I'm done talking to you now.", false); });
option1text.text = "Hello!";
option2.onClick.AddListener(delegate { goShop(false); });
option2text.text = "I wanna shop.";
}
else if (talkcount == 1)
{
talktext.text = "worked";
}
break;
}
}
}
void talking(string message, bool ran)
{
if (ran == false)
{
talkcount += 1;
ran = true;
}
}```
I would suggest you look into a premade solution like Ink
its free and learning it is not complex at all. Comes with its own language which is basically just markdown and can easily do branching
bleurg,,,,,, im using outside resources like that as a last resort
id rather learn this myself for future reference
well start learning basic things like arrays, scriptable objects etc.
hardcoding text isn't feasible at all
i know about the toby fox problem where he had the exact same setup and was chastised for it but frankly with the scale of my game i dont see it as a big issue
ehh with array you can easily switch messages but you do you lol
It works till you keep adding more and then hate yourself for making it soo hard to maintain and change
fair point
or others working on it hate you too
tbh whats the point of asking for opinions if you're going to shut them down because you're fixed on "your way"
my code is already an eyesore for othr people this is just adding onto tje pile lol
as long as you are aware of the potential issues as it scales then thats good
i asked for opinions on the code 😭
im taking in ur ideas but like
id like to know whats wrong with this right now lol
yes hence the suggestions of not hard coding things
even if i stop using it its just good knowledge
you want to have a switch with all the potential people you talk to?
wouldn't it just be easier to have each person have their own dialogue / lines
i feel like thatd just be the same problem but with scripts instead
unless youre referring to a way of doing that that i just dont know about
im assuming you mean a seperate script for each character
the only thing they would have is their own lines in an array , the script which you interact with dialogue just reads that,
but really!!! i just want!! to know!!! why this doesnt work!!!
on a coding level
not why it doesnt work as in why it isnt feasible
it does, but doesnt effect anything weirdly
i think the switch case is like paused somehow
also when i move out of the range of the character (resetting basically) it starts going up in 2s rather than 1s
then 3s if i do it again
its weird
no idea what that means
stepping through your code and see where things break down
you can also use lots of Debug.Logs but its easier to step through with breakpoints
Debugging , is first step identify where the code is going and what the values are
bleuurrg this is a mess ill just use ink
talkcount is good idea and you can combine that with array so index goes up, and line of text changes to something else. If you want you can make it an Object and still link a delagate/action to it (a specific line might want an action to run after it runs/before)
List<string> dialog = new(){
"Hello!",
"You suck",
"Bye"};
int dialogIndex = 0;
public string GetAndAdvanceDialog()
{
string msg = dialog[dialogIndex];
dialogIndex++;
if(dialogIndex >= dialog.Count)
{
dialogIndex = 0;
}
return msg;
}
even this is like indecipherable to me
you need basic c# before overtaking a dialogue system tbh
If you dont know what indexes are you do need to learn some more c#
nooooooooooooooooo id rather burn alive i hate watching tutorials about it
im doing fine without even knowing what a class is
have been for like 2 years
dont watch totorials on "how to make dialogue system"
(X) Doubt
like the things I suggested before, learn arrays/lists etc.
those are basics in all systems you make, not just dialogue
i know these concepts
just not c# specific stuff
or anything too highend
Low level you mean
im just giving an example of a way to use a list to cycle some dialog options
the more you know about programming the easier it is to do stuff
you need in practice not concepts, concept is good but you need real life experience coding and using them
i worded it wrong I Know and use arrays and lists all the time
then robs code should be pretty obvious what its doing
not ? really ?
literally just going through an array through index
i dont understand what the 'new()' does, or the 'public string getandadvancedialog()' and how those two are linked at all
He could of made it a little bit clearer
use arrays and lists all the time
new() does what the name implies
im on year 2 of an it college course cmon man 😭
it creates a new List
this is why we suggested basics refresh, this way it looks less scary
But it’s pretty simple
its simple enough I think
oh thats an odd way of doing it
So, question, how do you normally create an array?
And how do you normally write a function?
frankly the most experience ive had is the python version of a double stacked list so maybe im a bit out of my depths here lol
Then you should do the basic C# courses linked in the pins
dialogIndex++ had me for a second because I usually use i as a variable 😭
but this isn't python so this is misleading to say
I use arrays and lists all the time
You're kind of going to need to know how to write functions and basic loops
For indexes
Thats normal in a for loop but for a member var we want it to have a better name
this is the way ive been told to create a list public List<GameObject> pixels = new List<GameObject>();
i just stole this from my code
🤚
Yeah, see the new?
That's the same keyword
new() is just shorthand since you defined the type already
Just seeing the word new and knowing how lists normally work should lead you to know what that line is doing.
You can declare it with new or you can put it later in a function
And then the rest of it is pure basics that should fall into place
important part is know WHY you need new() when you don't for a number for example
If you see a thing you don't know, you can try to figure it out from context instead of just stopping reading and assuming you don't know this
//Simple way
List<int> myList = new List<int>();
myList.Add(5);
//Shorter way to make a list with some data in it already
List<float> someOtherList = new List<float>(){15.5f};
i know this
and i get most of the code in there
sorry im a bit overwhelmed with literally everyone talking so i cant say stuff properly lol
i literally said i only didnt get the two lines
Unity throws a curve ball where
[SerializeField] and public do not need =new() and throw a null reference
(serailizing in inspector the engine creates object with new() for you)
of 'new()' which i get now but Didnt because i just assumed lists are declared my way
Thats good. So in the previous example we made a list with 3 strings inside it already which makes it easier to write and change later.
but i still dont understand 'public string getandadvancedialog()'
ive never seen a line like that in my life i dont really have a frame of reference
you've never seen a method?

Public automatically does what seralizefield does right?
yeesh
not used on a string like that
yes, more of the opposite
[SerializeField] exposes private when public default is exposed in inspector
only with voids lol
if unity can serialize a type then a public variable of that type will automatically be serialized, yes
you should start with the basics of the language if return types are new to you. there are beginner c# courses pinned in this channel
well welcome to statically typed language ig
Why would you use serializefield private instead of just public? Does it just expose it for the inspector only?
the same reason you would make anything private instead of public. so that other types cannot access it
yes, and you don't want to keep everything public
yea usually we want to serialize a value but not let any old thing fuck with it in code
ideally you'd have no public fields

you may accidentally change something later on that dont need to be changed
I just write private always, and use public if I need to reference a transform
public get properties is the way, esp read only
And don’t use seralizefield at all
you can, doesn't mean you should 🙂
i have no stake in this conversation whatsoever but i just always set my variables as public lol
that's bad practice
I mean, it’s not like there can be any security vulnerabilities unless it’s a multiplayer game
its bad practice, unless you have the memory of a computer
never understood how you could accidentally assign a reference to it and change it
it's not about security vulnerabilities. that is never a concern when determining what access modifier to use. it's about writing clean code and conforming to SOLID principles
because its exposed, you later on might forget if its mean to be changed from elsewhere
private vs public has literally nothing at all to do with security
you can create a bug where you are now changing it through a field where its not meant to instead of a method that may need to run additional logic
You can get private fields by reflection
you lost me
good attempt
You can get to any field by reflection
right which is why public vs private makes no difference at all when it comes to "security"
Have you ever put your keys down in a slightly different place and then had no idea where they are and looked everywhere for them even though they're just on the cabinet by the door
I mean, you can call public methods but you can’t call private methods
That’s what I mean
//For anyone to look at
public IReadOnlyList<Stuff> CurrentStuff => stuff;
//Just for meeee
private List<Stuff> stuff = new();
Imagine you have a public MoveSpeed variable, and everytime you change it a Sound should be playing..
so you create a method that takes in a number and pass it to your movespeed, along with that it plays a sound in that method..
You later want to change moveSpeed from somewhere else through the field only.. suddenly your sound stopped working and you wonder why its "bugged".
(and forgot due to time, work amount etc. that it has a method you made for it to change)
im already drained from the last conversation these are just words being thrown at me at this pojnt
we dont know fire burns until we touch it and realize it.. so you may still need that
lol no idea this even existed 
A very useful interface to give a read only version of a collection so we dont have to make a copy!
(Because its read only it supports covariance and contravariance too!)
ah ok was wondering if this was any different than CurrentStuff => stuff
so i guess that makes a copy?
Its a property that just has a get. Its implicitly casting to IReadOnlyList
var notReadOnly = (List<Stuff>)myClass.CurrentStuff;
bet you like this too
https://en.cppreference.com/w/cpp/language/reinterpret_cast.html
Btw you cant cast NativeArray.ReadOnly to NativeArray
Or idk how cast
well these wrap some native memory so they can cheat
This is structs
var arrayRW = (NativeArray)nativeArrayRO; // not possible
ReadWrite has 2 atomics but ReadOnly only 1
I don't remember
You can get unsafe pointer this is cheat
I lowkey feel embarrassed because I should lowkey know this by heart cause I’m a 4th year computer science major but all I do is theoretical computer science 😭
Degree and actual application is not on par
Make sure you learn about source control like git/svn, some different design patterns and maybe tackle some interview questions.
haha yes using unsafe would surely help
Hey guys, how to set player x and y value, like how do I address them
adress them ?
uhm, like I got x as a variable, now how to I put it to work
playerGameObject.transform.position
pass it to the component that controls the positon
You probably want to start here
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
var playerPos = playerGameObject.transform.position; // get pos
playerPos.y = myValue; // change y value
playerGameObject.transform.position = playerPos; // set changes```
Is playerGameObject be replaced by this one?
(solved)
does this not break the loop?
why would it?
I assumed transform is part of a gameobject, so destroying them would destroy both
have you happened to look at the documentation for the Destroy method?
a very long time ago lol
consider looking at it now
oh wait
so it first iterates all of them in the current loop
and then destroys them in the next frame - is that right?
what does the documentation for Destroy say about that?
the objects are destroyed at the end of the frame, not the next frame
Incremental GC
hey so im following the tutorials from unity learn and in one of them it sais to use autocomplete to auto write a function but for some reason it doesnt autocomplete for me (and it never does even with other stuff related to unity) i tried fixing it on my own but that didnt work
!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
did everything in the instructions and now this pops up
when i download the SDK and reload vscode nothing happens and the message pops up again
also it still doesnt auto complete :l
I would close out of both programs: Unity and VSCode. Reopen Unity and double-click a script to open it in VSCode, then check if autocomplete works . . .
write dotnet to console
𝑯𝒊 𝒈𝒖𝒚𝒔
vs code console?
just powershell
yes
I would check to make sure the SDK is indeed installed . . .
it sais installation done
but then when i refresh the vs page the error pops up again
after i reload it
Try dotnet in a vs code terminal
Actually... You might be having the runtime and not the sdk.
what does that mean
There are 2 separate software pieces: dotnet runtime and dotnet sdk. Vs code needs you to install the sdk.
However, I'd address dotnet not being found in vs code terminal first.
ok i restarted pc
lets check
if it doesnt work im coming for u when u sleeping tonight 
Pls dont work
u were on the list too russian boy
-# also thanks :)
great , now i need help with my actual code
its not doing what its supposed to do (destroy the projectile and the entity)
📃 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.
A tool for sharing your source code with the world!
Its 2d game?
3d
bullet collider marked as isTrigger?
i dont have a collider on the bullet , just rigidbody with no gravity
thats what the tut said to do
Add collider with isTrigger
np
At least the first part was fixed, lol . . .
I would finish the tutorial to see if they add it or do any other stuff . . .
nn they didnt
most of the auto complete are working
but the one in the tutorial still isnt
the "void OnTriggerEnter"
That's weird. I can't remember if you need to install any extensions or not . . .
Need
downloaded all C# related extensions
You need Unity extensions
only 1 Unity ext is all thats needed, it already installs Devkit and C# ext for you
sometimes has issues install latest .NET sdk so manually install the sdk fixes
did all that
if they use VSC in vid, the video is probably old so the MB methods didn't show unless you got a separate ext
its not that old since its using unit 6
And vscode added in unity preferences?
yep
eh they took a while to add them but the're there.. anyway... as long as yours works thats all that matters
Hello! is this the right channel for some unity issues talk? (relative to coding and probably scene management)
true true , ty for the help and@vital barn too
guess

I guess it is, just wanted to be sure
its ok dude im jus trolling u , what do u need help with
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #🌱┃start-here
ahah alright! Let me explain!
Well.
I'm not really good at coding. I'm currently learning it.
Anyway I was following a tuto on how to make portals. I followed everything, tried to understand the line of codes I could understand. At the end the effect looks really good!
Unfortunatly the cameras that displays the other side of each portals doesnt place well. Even when I teleport to the other side of the portals, both cameras starts to go off scene.
(here's the tutorial I followed : https://www.youtube.com/watch?v=VituktEvIY8
also sending my portalview code)
In this video we will make a portal view ,so can see what's on the other side. Enjoy the tutorial !
❤ Complete courses at - unityalexdev.com
❤ Complete RPG course at - unityalexdev.com/rpg - [85% discount]
grid textures - https://assetstore.unity.com/packages/2d/textures-materials/gridbox-prototype-materials-129127
❤suport me...
Let me send also a screen of the issue
on the other side of the door, I'm seeing myself eventhought I'm supposed to see the other door
and that is due somehow to the camera not positionning well, and I have no idea why unfortunatly
Sorry for the big spam
was gonna say smth , realised ts too advanced for me mb i cant help (others will do so hopefully)
oh alright no problem, thanks thought!
do u accept dms btw
I do!
Try without void. Does it still not show up?
Trying to follow a tutorial. This is my code. Next image is his. Am I missing something because I'm getting an error
my python experience is telling me I'm missing one tiny semicolon or smth but I don't see anything lol
- is not = (:
Note that your IDE is not currently working correctly
It should've highlighted an error there
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
this guide will make sure that Visual Studio is working correctly
this is the error
spelling is also wrong
hmmm something is still not working
I'm gonna go through the VS guide but there's something up with the indentation or something because the text at the top like MonoBehaviour should be colored
that's not an indentation issue, that's your IDE not being configured
Unless C## isn't like python where colored text matters
yes thats why they said to configure it
whats color got to do with a coding language ?
the Editor is whats trying to color known keywords / types
white text = you messed up somewhere (in general)
your IDE does not understand that this file is part of a C# project
therefore, you need to follow these steps
I am trying to, but I don't see "Modify" anywhere so it's taking me a minute
I wonder if they changed things in the 2026 version or something because I genuinely don't have a way to follow these steps
Are you looking in the visual studio installer
Yeah but it doesn't have this
show what you are seeing instead
No Gaming category at all
but by clicking around in the unity hub it looks like I just have to download the 2022 version?
did you scroll down?
2026 does work with unity, it's just that 2022 is what is currently automatically installed. but have you scrolled down in the workload view?
yes
hold on I have an idea
🙃 So I noticed there was a weird gray area where something didn't load in. I just restarted my computer and booted everything back up and there it is
sorry to be a pain folks 😅
FINALLY okay after installing 12 billion things I got it to work
I was asking about this earlier and found a solution but have a new issue...
So im using abstract Scriptable objects for the abilities my player uses.
I like the drag & drop functionality. Its working well for my single player who would ever use them.
For the sake of wanting to use this code for other projects in the future i tried to allow my enemies to use these abiliities as well.
Everything works except a quite predictable outcome that Scriptable objects are static So if 2 enemies try to use the "laser beam" abiltiy at once it acts weird, because i store a "currentLaserPrefab" in the Scriptable object itself.
I understand the issue but im not sure what do about it.
I guess i would need another script to contain data like that per character that might use it but it defeats the purpose of drag and drop abilities.
Any thoughts?
Keep static data on the SOs, use runtime/mutable objects in memory for runtime data
What does currentLaserPrefab mean though? The prefab for the laser changes at some point?
Its a continuous laser beam weapon. that keeps fireing and updating as i hold the attack input.
So i have it instantiated then i keep the [currentLaserPrefab] to reference it.
I call it that for my sake
[laserPrefab]
[currentLaserPrefab]
sounds convienent for me
If you instantiated it, the instance is not a prefab
sorry that variable name confused me
Shouldn't it be currentLaserInstance?
prefabs are the things that live in the asset folder, not in the scene
But basically. I'm not sure exactly how your game/code works but I would probably structure it something like this:
public abstract class WeaponSO : ScriptableObject {
public GameObject projectilePrefab;
}
public class Laser : WeaponSO {
// whatever specific laser stuff
}
public class Player : MonoBehaviour {
public WeaponSO equippedWeapon;
public GameObject weaponProjectileInstance;
void Shoot() {
weaponProjectileInstance = Instantiate(equippedWeapon.projectilePrefab);
}
}```
This way weaponProjectileInstance lives on the MonoBehaviour for the individual player
it's not stored on the ScriptableObject
I want to do something very similar to this (and will) but im worried about the Shoot() method
Shoot shouldnt care what my ability is, just that whatever it is should shoot or "Activate" when called
If i try to use a different ability that doesnt have a prefab then wouldnt it flag?
OnDrag() only works with UI elements ?
I am not getting the behavior of the paddle ball to work. It goes straight up into the air, but I want it to go in any direction and when it collides with a collider, whether it is me or a block it bounces again like a normal ball. Where did I go wrong here?:
if (playerController.ShootBall==true)
{
// Calculate the impact point relative to the paddle's center (-1 at bottom, 1 at top)
float hitPoint = (transform.position.y - collider.transform.position.y) / collider.bounds.size.y;
Vector3 newDirection = new Vector3(Mathf.Sign(ballRb.linearVelocity.x) * -1, hitPoint).normalized;
acceleration++;
ballRb.linearVelocity = ballRb.linearVelocity.normalized * (initialSpeed + acceleration);
}
}
Then make it an abstract "Use" or "Activate" function
It works with anything provided you've got the right set of components involved.
What's the context of this code?
this is on the ball script
when I press space the ball fly to hit an object and bounce from said object like the one in paddle game
but now it goes straight up as if it is a flying rocket
is there an int version of mathf.pingpong repeat ?
any scenario where it give the undesired output when cast (int) on float?
depends on what the desired output is
it's truncation
will 1.9999 became 1 then
also is there an int version of mathf.pingpong repeat ?
PingPong seems to be just a triangle wave, so you could make an integral lerp for that
Repeat is just modulus/remainder
fr
is there a proper way to set an images color? i made some WHITE sprites in aesprite and i set it up like this:
i import the image and turn off compression and set the filter mode to point (no filter)
i create an image in the heirarchy under the canvas (as usual) and i set the sprite to that WHITE image.
during runtime, i set the color like this
imageVar.color = Color.white;
and while the image is still there, you cant see it anymore. it makes me think of that one time a long time ago an image file i had corrupted somehow and while i knew it was still on my drive i would never get to open it again because the file is corrupted.
why are you using fixeddeltatime in update
-# in response to a deleted message
does this sun have any other components, eg a rigidbody?
the color is multiplicative, if you weren't aware. probably not the cause of the issue, would need more info to say
my AI Claude said that the multiplication is the reason why pure white was the best option. didnt stop unity from screwing me over still.
yikes, ok
in aesprite i made sure it was pure white
that's.. probably not related
yea cuz if it was mixing in a black pixel id still get a color
without more info i'd guess it's probably rendering orders
try asking in #📲┃ui-ux with more info about your setup
setting it to any color makes it dissapear
what if you set it from the inspector
Can you share the original image?
ill send one of my 20 something ones
it took me hours to make my own image of a ps5 controller and then break it down into parts
i did it pixel by pixel
and also used the bucket ofc
i was thinking that unity made a new dumb modern way of doing it with code but kept it secret so much that even claude doesnt know about it
ok maybe stop relying on AI
have you tried doing it with the color structure
Color.white is using the Color struct
oh yea also setting it in the inspector during runtime works fine. and yes i was using the color struct
im in unity 6.3
show the inspector from when it disappears
here. i have my code on start setting all of the fillers except for the thumbstick ones and the 3 parts that are not with a btn to Color.white. i lumped those 3 into the List<> with the others so the changing to white with code before anything else happens to them too.
literally i got everything else working fine but for some reason i still cant set a color with code.
any unity version i use has this problem
I'm not sure what your code is exactly but this color has an alpha of 0
so whatever object this is will be invisible
you can tell because of the black bar at the bottom
My guess is you have a bug in your code setting the alpha to 0
if you need help finding it - feel free to share your code here
Same thing for all the colors in your video
what is a colors alpha? i had no idea that was even a thing.
next time im on ill also set the alpha to max
in the code
Color has 4 fields - rgb and a
(alpha)
alpha is transparency
0 means fully transparent
maybe share your code so we can see what the issue is
cuz all i do is set the Color to Color.white.
I'm guessing you're doing something else as well that you forgot about
maybe there was a setting in Aseprite i wouldnt have thought to look for.
ill ask my friend whos a pro with that app as well tomorrow
this isn't an aseprite issue
this is the color on the Unity Image component being set to alpha 0
Aseprite would have nothing to do with it
oh
-# technically alpha is opacity in this context
ive already turned my pc off for the night so ill be back tmrw
its past 3am and i gotta wake up at 8 for my opening shift 😢
Hey, I know this isn't technically for beginners, but i'm a beginner, could someone help me create a friction system in my game?
For now, the game is very basic. I already have some movement with AddForce, but I really need to add friction. Also, I already have a system to detect if my character is on the ground, which is necessary for the friction system, if I'm not mistaken.
[Screen 1 : Movement/Jump] [Screen 2 : Ground Detection]
Do you know that friction actually already exists in the physics engine?
Why not use a material with friction?
because I would also need friction for the air
No one has ever mentioned it to me. No one ever told me about it. I was told to create one.

I feel a bit stupid.
Im pretty sure you can still use the physics engine for that lol
Use dumping property in rigidbody
It's possible, but I need to find some guides on the internet because it's not within my capabilities at the moment.
I think everyone makes a similar mistake when first starting lol

I've tested it a little, but I have to admit, I find that it makes everything seem rather archaic.
I think I'll try to do mine anyway. I don't know if you'd be okay with continuing to help me. I don't want to be too much trouble.
The little game I'm planning is really based 90% on movement gameplay, so I really want to get my hands on it.
I'm going to watch this video even though it's long. https://youtu.be/3lBYVSplAuo
In this video, I am going to thoroughly go over everything about physics in game development. Regardless of whether you are a complete beginner and don’t know what a force is, or a seasoned game developer who uses physics all the time, I can almost guarantee that you will take something new away from this video. This is the ultimate guide for ...
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
is anyone able to explain why when im unloading my old scene the canvas is like half rendered for a split second?
you can see what i mean in the video
my setup is just a overlay canvas in my main menu scene
and then im switching to a scene which just has a overlay canvas
no scenes have any cameras since its an overlay canvas
ignore the scene switching for now i discovered its happening here as well
"Interface" is my canvas and i added a image gameobject to it covering the rest of the ui
and i made a script which simply sets the game object not active
im on unity 6.3 lts
probably just screen tearing, is vsync disabled?
it is disabled
its also a fresh project
i just made a project on 2022 and it works properly
im making a even fresher one on 6.3
this is unity 6.3 fresh project
this is unity 2022 fresh project
this is half way through disabling the image object
wait unity 6.3 has vsync turned off by default let me check if it helps
it was screen tearing
but idk how to fix it without having vsync on
i tried limiting the fps to the refresh rate and it didnt help
I'm starting to get the hang of Dampling, but I'm still asking: does anyone have any resources to help me understand the system better?
wth is 'dampling' ? 😄
guh
damping
few things
- friction with other solid objects and with the air already exist. Its the physics material and drag setting respectively
- you really shouldn’t use either, or AddForce for a platformer unless you want a particular physics-y (and kinda janky) feel. You are much better off just setting the velocity directly. “Friction” is usually implemented by gradually lerping the X component of the velocity to 0 when no movement is pressed. You can have this happen faster or slower in the air, but thats just a modifier on it
Thank you, that's very clear.
In addition, I've done quite a bit of research since earlier, and I've understood a few principles, if only in how to use C#. Yes, I'm that much of a beginner.
!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.
void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector3 finalInput = verticalInput * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
}
void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector3 finalInput = new Vector3(verticalInput.x, verticalInput.y) * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
}
which input and movement makes more sense?
Did you get this from somewhere else that you arent sure what this is doing?
These look to be doing the exact same thing. Add logs to see the value of that finalInput to verify this
no im learning input and movement myself, I wrote this myself as well, they are doing the same thing in Unity on playmode but they both compile as well so Im just wondering which way is the better way of thinking about with Vectors
Neither one is better, its both the exact same thing. Vector2 can automatically be converted to vector3 because unity defined this conversion. It just assigns 0 as the z value
like do i need to create a new Vector every cycle in the bottom solution or the first solution is the better one which updates the same one i think?
Either way you're creating a new vector. Creating a vector is extremely cheap here. I guess the only possibly difference here would be the bottom solution is doing more operations since youre converting to a vector3 before multiplying. So its multiplying all 3 values by your speed and deltatime, rather than multiplying 2 values and converting to vector3 after
This is extremely negligible though
Ooh okaym, so either way Its creating a new Vector3? I didnt know that
When the vector2 is implicitly converted to vector3, it has to create one. Its a struct though so this really doesn't matter
U could create 10000 vectors every update and probably see no performance difference
the conversion happens in the first solution right, the second one creates a fresh new one
Yes but the conversion creates one the same way you do
And I didnt quite understand which one is doing more operations since im converting to a vector3 before multiplying like you said
the "conversion" is just creating one and copying over the values, like in the second one
it really doesn't matter here. it's nanoseconds
yeah I got that thank you, but I dont get what bawsi said about converting to a vector3 before multiplying, so its multiplying all 3 values. Thats what I didnt get, how is it converting before multiplying?
so this line creates a new Vector3
new Vector3(verticalInput.x, verticalInput.y)
and then multiplies
* (movementSpeed * Time.deltaTime);
where does the conversion happen first?
in the first one, you have a vector2 where you multiply each component, so 2 multiplications, and then you turn that into a vector3
in the second one, you have a vector2 that you turn into a vector3, then you multiply each component, so 3 multiplications
I dont understand 🙁
which part exactly?
in the first one I have a vector 2 input which is used to create the vector3 final input variable, which has three floats no?
do you understand the difference between these 2
Vector2 original = /* ... */;
Vector3 a = ((Vector3)original) * 2;
Vector3 a = (Vector3)(original * 2);
yes
but why is it two multiplications then?
you said it yourself? the conversion happens before multiplying
this line creates a new Vector3 and then multiplies
because it's converted to a Vector3 after the multiplication
unfortunately no
the Vector2 from here
the result is a Vector2 still
so the difference is that first its converting to a vector3 then multiplying by two and the second solution is multiplying Vector2 by 2 then converting to a Vector3?
yes
void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2();
Vector3 finalInput = new Vector3(verticalInput.x, verticalInput.y)(movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
}
so that just doesn't make sense
so this code referes to ```cs
cs
Vector2 original = /* ... */;
Vector3 a = ((Vector3)original) * 2;
its the same right
it's not valid, you can't call a Vector3
what do you mean? its compiling and working
are you perhaps missing a * in that snippet
void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector3 finalInput = new Vector3(verticalInput.x, verticalInput.y) * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
}
right, that's converting to Vector3 and then multiplying
so here the conversion happens first and then multiplication with movement and deltatime?
okay so now how does verticalInput multiply three times here
if its only ```
cs
dammit
verticalInput.x, verticalInput.y
if its only this, how is it three times
or it multiplies that z value too
yes
okay so it does it by itself automatically we just dont have to type it out
it's not "automatic", this is a function that unity devs have written explicitly
okay so vertical input multiplies with three values x y and z converts to vector3 then multiplies with movement speed and deltatime
yeah that function does the work for us ^^
multiplies with three values x y and z
not sure what you mean by that
the 3 multiplications were from when you multiply by movementspeed*deltatime
ooh
there's no multiplication happening in the conversion itself
so I just get a vector 3 by assigning the vector2 values and a z value of 0 then multiplying all three values of that vector3 with mvoementspeed and deltatime
finally i got that, okay now how does the first solution have only two multiplications
because it's multiplying a vector2
void Update()
{
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector3 finalInput = verticalInput * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
}
okay so this is multiplying that vector2 with movementspeed and deltatime and unity is converting it to a vector 3
c# is doing the conversion, not unity
unity specifies how to do the conversion, and that the conversion is possible
understood, so its easier to write and on a microscopic level better to write like this?
technically yes
at this scale, the benefits of being easier to read/write/maintain far outweigh the increased speed of 0.000001%
yeah reading and writing is def easier this way, thank you for your patience and explanations, truly appreciate it.
since im learning I want to understand why and how code works, not just blindly writing out syntax
if you want to get into the nitty gritty details i'd recommend learning C, it really helps understanding all the underlying concepts for various syntactic sugars like this
(or even asm, depending on the level of detail you're interested in)
learning C as in just the syntax? Or youre recommending to get into lower level stuff?
the details of how stuff works at the fundamental level, and then you can kinda see how syntactic sugar maps onto that
this is already hard enough for me as is, I think getting even lower would be just too difficult to grasp, English isnt my first language too, makes it harder to learn on top
but yeah like i mentioned this is kinda really deep details already
i thought reading a book about game math
there honestly isnt that much to learn about it unless there's a specific feature you want to implement. the only thing here was the difference of when a vector2 was converted into a vector3. In one case, you manually created a new vector3 before multiplication happened. In the 2nd case you did multiplication then converted it to a vector3
If you're trying to learn vector math, it doesn't have to be in a game context because it's still just math at the end
unity provides most of the math you'll ever need. under the static methods
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Vector3.html
oops I wrote it backwards, in the first case you did the multiplication first then converted. In the 2nd you created the vector3 then multiplied
yup yup I understood it anyway ^^ thank you too. I guess im just struggling with multiplication in general, what to multiply with first or what at all or the general order
tried making a third person camera rotating around the player with zoom and it was hell, I did manage to make it work but I would be lying if I said I made it myself, I just used what I found online and glued everything together. Quaternions are hell for me so im starting from basics in 2D space again
quaternions are hell to everyone tbh
just treat them like a black box and only do the public operations
Hey! Just in case I still need help on this, if anyone is interested in looking at it!
!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.
would help to post your code appropriately ^
it's also not super clear what it's supposed to be. this door is supposed to be a portal, right? where's the exit?
@naive pawn I have another solution could you maybe give your input
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
transform.Translate(verticalInput * (movementSpeed * Time.deltaTime));
this seems to work as well
is it the same as my previous solution, but the calculation happens in the Translate parameter?
Vector2 verticalInput = moveActionReference.action.ReadValue<Vector2>();
Vector3 finalInput = verticalInput * (movementSpeed * Time.deltaTime);
transform.Translate(finalInput);
the compiler will generate the same thing, the upper solution might be easier too since I dont have to create a separate Vector3 but maybe would be harder to use if more logic would be involved in the future?
is my thinking right?
solution 2 is always cleaner
if needed to debug it, you can easily pass it to another function. Like Debug.Log without touching anything else
yep that as well, thanks for your insight ^^
so generally its better to keep the calculations out of class methods and just use the final variables inside of the parameters correct?
its not a hard rule. Imo mainly for clarity and such, I say it is
okay makes sense to me too
same thing here where I can just calculate the direction towards the player like this
Quaternion lookRotation = Quaternion.LookRotation(playerTarget.transform.position - transform.position).normalized;
but its better to do it like this
Vector3 direction = (playerTarget.transform.position - transform.position).normalized;
Quaternion lookRotation = Quaternion.LookRotation(direction);


