#💻┃code-beginner
1 messages · Page 754 of 1
nothing you dont need the loop it was an example how to print each number but thats not relavent anymore
similar to a for loop except you dont iterate with an index
some basic c# courses would probably do you good here tbh
you wrote some nonsense and crashed your intellisense xD
Why are you trying to foreach that
idk cause you're copying blindly lol
No, this is on you
I'm doing what y'all are telling me
Why are you using foreach
I have no idea, it was suggested, so I'm using it
Why are you looping over anything?
we're just showing example what each thing does, you don't have to copy every line to shuffle it randomly around
if you only need to do something once, there is no need for loops..
You should actually try to learn what these functions and keywords mean
I sent you the documentation for foreach
I should've used explicit types to not confuse things more var 🥲
You should learn what it means
how do you do this? I know there should be some way of extracting stuff from the interface object but I can't remember how
EntityHealth implements IEntity
wait no it doesn't ignore me
rubber ducky moment
also consider entity is EntityHealth healthComponent as a condition
defensive coding standards
I did originally but I thought it was wrong since it errored
what does the error say
turns out I got my classes confused, EntityHealth doesn't implement IEntity
it was a different one
yeap make sure to actually read the errors
if it's a syntax error, you wrote it wrong
this, but yeah it's literally just because the class never implements the interface 🤣
if not, you're using it wrong
jfc
can somebody help me on what this is?
bro really posted a mobile screenshot of GPT code
what what is, exactly?
ask your spambot to explain it then
yeah, what about it? i’m a beginner bro.
we dont help with ai generated code
how do I ask my spam bot?
"explain it "
though take the info with a grain of salt 🤷♂️
and then pray you hit the 50/50 that it isn't lying
where’s my spam bot at?
the one you got the code from
Ok
what about it
It appears to be a screenshot of code
hope this helps 👍
Yooo can somebody help me make this game? DM it’s for VR
No
$500k salary?
!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**
Am ok
if you have specific questions you need help with, you can ask in the appropriate channels. but don't come here with genai as a source lmao
i’m not a scratch to that money, bro
I need to reference UnityEngine.CoreModule to allow for this line:
if (PerkMemory.lastGeneratedPerk != null)
to work. because It references a scriptable object.
Doing so causes:
Debug.Log($"Test1");
To throw an error because "Debug" Exists in both UnityEngine and UnityEngine.CoreModule.
So I'm in kind of a loop where;
If I have "using UnityEngine;" At the top of my cs file it causes mentioned error. Removing it causes Debug to "not exist".
In my csproj file I added a reference to UnityEngine.CoreModule. Removing it fixes the duplicate issue but then my if statement doesn't work as it references a scriptable object.
Lost on what to do
here's the proj file. I'm just building off the template plugin bepinex has in it's documentation
If you need any specific information from the plugin file just lmk
UnityEngine.Debug.Log
Are you saying to write that instead of the written line for my Debug? Because that does not remove the error.
I tried that already, tbh I'm kinda stumped why that doesn't work
What does the error say when you use it
Debug.Log
&
UnityEngine.Debug.Log
Give the same error
CS0433: The type 'Debug' exists in both 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
Okay so this isn't some basic IDE ambiguity, this is actually the same namespace in both which is a problem. Why do you need CoreModule? From looking at it, it should just be included
Removing:
<Reference Include="UnityEngine.CoreModule">
<hintpath> [Truncating for brevity]</hintpath>
</Reference>
From the csproj file causes the following error:
CS0012: The type 'ScriptableObject' is defined in an assembly that is not referenced. You must add a reference to assembly 'UnityEngine.CoreModule, Version=0.0.0.0,
Why are you modifying your csproj
Unity generates that
I am not making a unity game directly I am making a mod for a game that I only have decompiled. I am sorry I didn't mention sooner. The game is White Knuckle.
We don't do mods here
weird
specifically because they impose these kinds of nonsense problems that never come up in normal unity contexts
Ah.
I wanted to get into Unity so I could make a 2d turn based strategy game, any advice for the first things I should be doing?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
start with essentials then junior programming etc.
Alright, how long should getting through this take..? I know it all takes time, but I am generally someone that lacks motivation, so I'm running purely on willpower to make this game
no idea. that depends on you
I get that
especially when it comes to learning
normally I'm motivated by learning something new then put it into reality
I guess my motivation would just be that I want to make this concept for a game actually real
learn more generalized concepts for your project instead of trying to do it all at once
if you have prior experience you could immediately start working on your game right off the bat once you familiarize yourself with unity
Barely any, I did some stuff with scratch.
I am pretty good with ideas and thinking of what to do, but my actual technical skills like coding and stuff are poor
but otherwise youre going to need to learn some fundamentals
learning c# is already its own thing, throw Unity and its concepts ontop of that.. there is a LOT to do
yeah
I tried getting into Luau a while back, but got over it since my friends who were supposed to help me with the game gave up
imo start with unity learn
I'm guessing making this game would probably take like... 2 or 3 years if im lucky
depends on the scope
learn pathways will give you a little taste of what the processes are
I'm aiming for something similar to LoR
legends of runeterra?
Not as big of, or as high quality of a story, but something similar to it
Library of Ruina
Turn based strategy, story driven game
well both of those things are 2 seperate beasts to conqure
Yeahhh
you should start working on a basic strategy system, tinker with that and then see what you can do with it
The only leg up I have at the moment is knowing what I want for the game design
after you go over the fundamentals
Yeah, I got a basic concept written on a doc
i mean thats nice but its pretty much useless right now, because you dont actually know yet what you can pheasibly do
True
i say focus on the fundamentals and try and tinker with individual systems, start very small and see where you end up
you never know what this concept might later turn into
it could be something completely different, for better or for worse
most game design docs dont get realized until some development overhead was made
Yeah, that makes sense.
its rare for someone to hit the ground running with a fully realized concept because its pretty common that you will hit roadblocks you cant overcome meaning you will have to adapt, and so will your idea
The biggest issue will be incorporating gun mechanics. As I plan for different guns to have unique functions
thats something a lot more specific
but trust me as you learn the basics the knowledge for creating the more complex systems will come to you naturally
good luck :)
That's why I joined here, I plan to ask around for help and so forth
ty ❤️
eyy anyone that could help me with this im trying to make so u can cut down tree and after it falls to cut it even more for smaller pieces and stuff but im stuck haha
stuck with wat exactly
generally:
make two version of tree, one solid
another with already chopped pieces / possibly physics based (hidden/disabled)
when you chop it down, activate the second version
ye so i made it kinda work when u start chopping a line appears on faces of tree (its just cube for now but im thinking of sticking for cubed trees and lowpoly) that line is like progress bar fills as u chop when u chop tree falls stump appears down but when i try to cut on smaller pieces that fallen tree those lines arent coming or arent on tree good positioned
sounds like a more technical question then
can you show us the function you use to create those "lines"
There's no command called
paste.
📃 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.
those lines are cubes that spawn around tree and scale to fill
why not use decals ?
idk im new to this more complicated stuff haha it lets me cut down tree lines come stump spawns but doesnt let me cut it when its fallen and to split it (i also want to add to grab and lift up tree with press e to rotate it in air and stuff) https://paste.mod.gg/gewamtvblwxp/0 idk u can see code here
A tool for sharing your source code with the world!
Hi all - I'm trying to use the first person character set up from com.unity.charactercontroller. I've been following the get-started docs on it but having an issue of the character "falling through" the ground plane. The plane has a box collider as do the components on the first person character set up. I first person character set up is also a little above the plane. Any idea what could be causing the issue?
does it maybe use some kind of ground check layer?
you do know thats the package for ECS ?
oh nvm
I don't know what that means 🥲 I'm just trying to follow a tutorial and unsuccessfully retro-fitting it to my needs
what tutorial has you using the character controller from the ecs package?
unless you think that page is the tutorial
which tutorial ?
What bin do you guys recommend for code dumps?
!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.
Oh shoot sorry didn't notice this was the code specific channel - thought I was in the normal unity talk. Ty nav.
is there a way I can get the dll generated from the assembly definition file copied to a specific path?
assembler
what is that?
How are you generating the dll? Or do you mean the dolls that are put in the library folder?
the ones unity builds yes
Might need to hook to some editor events and do the copy in your code. On assembly reload or something.
Would be awesome if they let us define post build cmds in the assembly definition file 😭
AFAIK the Library folder is used for cache, nothing get built there - when you create a assembly definition file, it creates a .csproj file in the root of your project folder (just outside the "Assets" folder), where "Assembly-CSharp.csproj" exists and if you have editor scripts, "Assembly-CSharp-Editor.csproj" exists - those are what shows up in VS, unless your talking about a completely different file?
when unity editor builds it generates dlls for the assemblys in your project in Library\ScriptAssemblies
I was just wondering if a copy to feature was built in
UnityEditor.Compilation namespace, especially compilation pipeline class, contain events related to assembly compilation. You can hook to on assembly compilation complete, check the name of the assembly and do whatever you want from there.
In order to run that code(even in the editor), unity has to compile it into a binary.
And that's what it's doing. It's saving it to the library since it's indeed "temporary cache". It's only required for the editor to run this code.
Ah I see, that makes sense
Good morning fair folk of the Unity persuasion 🌅 I've got a question regarding UI architecture and mindset.
I'm currently learning how to set up multiplayer functionality, and first iteration of the lobby functionality is done. Naturally, i want to see the results reflected in a basic UI. Now, i'm curious how you guys and gals think about your UI when you set it up. Do you make it a singleton and update it via events? Do you create different UI documents for different sections of the UI? For example, would you keep the UI doc for a "Inside Lobby" separate from one that handles, say, "Create Lobby"? I like singletons and events, but I would very much like to move towards more decoupled patterns. Now, UI might be one of those instances where a singleton fit like hand in glove, but even if i just think back on the last project i did, keeping the UI elements for the "Outside of game"-stuff in the same Visual Tree Asset as "Inside the game"-stuff quickly felt bloated.
Any pointers? 😄
what do you mean by outside and inside ?
Apologies, that was poorly worded. By outside, i mean the layout and controls you see before starting a game, such as a "Start Game" button, and the inside would be for example and NPC dialogue box. I'm not sure what the correct terminology is to differentiate between these two game states.
oh i have never done ui for multiplayer but for solo
you can create a global struct then create Button function that link to your game (decoupled is good but not everything can be decoupled)
As multiplayer , you can try to preload the UI in async you will need like when I start game
preload ui for Start, Setting UI
then if I press Start -> change to UI
then preload Pause, setting , etc
This is what i would do if you don't want to preload all layer
But if you load all at once then
you can use a enum to know where you are in the UI
public enum ePanelType
{
NOT_DEFINE,
DIALOGUE,
MAINMENU,
HUD,
SETTINGS,
ENDGAME
}
Something like that and you setup all layer in dontdestroy
(ps: i am also a beginner , there must be better way)
I had to install the new visual studio since 2022 was retired but now my updates and awakes don't work!?
what do you mean, there's 0 references?!
it's an monobehavior
that's correct
it's just that it's greyed out.
you shouldn't be calling unity messages in your own code, so they shouldn't be referenced in your codebase
ah. ok, yeah that shouldn't be happening
!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)
make sure it's configured
Hello, I've a question, today I start to code my item and inventory system so I start with Item system, first I've created scriptableObject ItemData and after 3 other class WeaponItem, QuestItem and ConsumableItem, inherited from the itemData class, after I'ce created the abstract class ItemEffect for create special effect for my Item, like healthEffect for potion, or chargeEffect for batterie etc etc, my question is : Do I create a class for each Item Effect, or do I create several functions where each function represents an effect in my ItemEffect class ?
What is your advice
I think the WeaponItem, QuestItem, etc classes are a mistake.
Just give ItemData a List<ItemEffect>
Oh okay, and I create all the Item with the ItemData ?
public abstract class Shape
{
public abstract float CalculateArea();
}
public class Rectangle : Shape
{
public float width;
public float height;
public override float CalculateArea()
{
return width * height;
}
}
public class Circle : Shape
{
public float radius;
public override float CalculateArea()
{
return radius * radius * Mathf.PI;
}
}
instead of doing things like above, can't i just do it like this instead:
public class circle
{
public int radius;
public int GetArea()
{
return radius * 3.14F;
}
}
public class square
{
public int side;
public int GetArea()
{
return side * side;
}
}
I don't understand the benefit of having a base class which has an abstract method if you end up having to specify what the method has to do in the derived classes anyways
things that know about just the shape as a shape can call that function knowing some intentional implementation will exist
Given your second example how would you write a function that calculates how much paint is needed to fill in any shape?
You would need to write two functions, one for a square and one for a circle
you won't cus you would need to code it out differently for diff shapes
The abstract class eliminates that need
Nope
but i did do it though?
If it's just based on the area, you can use the abstract GetArea function
but the thing asking the shape for the area doesn't care about how it's being done, it doesnt need to know if its a square or circle it just knows its a shape and it wants the area from it
You had to write different GetAreas yes but code that depends on the area of a shape shouldn't have to care about what kind of shape it is. You don't want to have to write such code over and over for every shape
but i would have to create such a code over and over if i were to create diff shape classes in the future no?
yes but the thing using the function doesn't need to know that
i do understand your point, trust me, but i find it redundant as a usable concept
if you had eg.
Employee : class
abstract void DoWork()
there might be many different employees with many different representations of what DoWork should entail, but all employees do work. and if say a boss finds a Employee instance, it doesnt need to know if its a Cashier : Emplyoee, ShelfStocker : Employee etc. it just needs to know its an Employee for it to tell it to do work
i need an example to understand why it would be better to create an abstract class in such a scenario
Having all your shapes come from a single class allows for some useful things, like lists of different kinds of shapes where you can call the same method name for each shape and have it do different things (like the CalculateArea function)
abstract means "i dont know how your going to do this but you do need to do this". it's basically a promise
You can also just make a variable with the type Shape that can hold any type of shape and then call any Shape method, specific to the type of shape it’s holding
another random example is if i had a bunch of random toy wooden shapes in a big box
and i wanted to iterate over them to find the biggest one
i dont need to know if the Shape is a Cube or Sphere because i can just get the GetArea() function knowing whatever it is will give me the right answer
but that shape does need an answer to that question in order for it to be a valid shape
just one time per shape for the things unique to that shape, that's it
n * the work instead of n * m times the work
could one of you code out the main part of the code? i think i will be able to understand why your points are valid if you do so
because i feel like this is an important part which i would only understand once i see the main part of the code which actually ends up calling getarea
With abstract parent (just a single function that works for all shapes):
float CalculatePaintAmount(Shape shape) {
float area = shape.GetArea();
return area * PaintPerSquareMeter;
}```
Without (You need a separate function now for each shape):
```cs
float CalculatePaintAmount(Square s) {
float area = s.GetArea();
return area * PaintPerSquareMeter;
}
float CalculatePaintAmount(Circle c) {
float area = c.GetArea();
return area * PaintPerSquareMeter;
}
float CalculatePaintAmount(Triangle t) {
float area = t.GetArea();
return area * PaintPerSquareMeter;
}
lemme try coding this out
Hey can sombody help me, i want to reference a Dust Particle from a Script. Everthing is working, but i wantet to programm a small fallback for a GameObject search. (just to get a better feeling of Getting Components etc.) but my Code cant find the Gameobject with the name "ShootDust": This is my Code private void InitliazeVFXShootDust() { if (VFX_ShootDust == null) { GameObject target = this.transform.GetComponentsInChildren<Transform>().Select(t => t.gameObject) .FirstOrDefault(go => go.name == "ShootDust"); } }
the Dust GameObject lies under the Player. i wanted to search throught every Transform and use the searchohne "ShootDust" and get his Component
how do you know it's not working?
(This isn't good practice btw)
i testet is out
how
palying the game, search in the Inspekor. it was empty and also the dust didnt Spawned
nothing in the code you showed would show up in any inspector
it does, i search the Script Reference for the VFX Manager. It updatetet the Reference field in the Inspektor
the code you showed doesn't update any fields
The code you showed simply creates and immediately discards a local variable
it cannot and will not be useful for any purpose the way you have written it
Nothing here sets anything visible in the inspector or spawns anything. If you have more code than this that does you should actually share it
okay i can share my code
!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.
A tool for sharing your source code with the world!
yeah it's teh same here
but every time i search a Scrpt with GetComponentsInChildrewn he updtades the Field in the Inpektor
InitThe InitliazeVFXShootDust() function does absolutely nothing of worth
which field
why?
because it simply creates a local variable which is used nowhere
Okay so you just aren't setting any variables or spawning anything
You didn't leave anything out you just simply are not doing that
i did i use a method in the VFX Manager Script
which field are you trying to update
Which method
Is this what you are trying to update?
[Header("VFX References")]
[SerializeField] private GameObject VFX_ShootDust; ```
yeah
wait
you would need to actually do VFX_ShootDust = something;
it you want to update that
this target variable is completely unrelated to it and will not affect it
Then you need to actually set that variable to something
hmmmm u right ofcors
Notice for example this other function:
private void InitliazeShootOringn()
{
if (shootOrigin == null)
{
shootOrigin = GetComponentsInChildren<Transform>().FirstOrDefault(c => c.name == "ShootOrigin");
}
}
using System;
using System.Security.Principal;
public static class Shape
{
public abstract float GetArea();
}
public static class Circle : Shape
{
public int r;
public override float GetArea()
{
return r * 3.14F;
}
}
public static class Square : Shape
{
public int side;
public override float GetArea()
{
return side * side;
}
}
float CalculatePaintAmount(Shape shape)
{
int PaintPerSquareMeter = 10;
float area = shape.GetArea();
return area * PaintPerSquareMeter;
}
public static class Program
{
public static Main()
{
Circle c = new Circle(r = 4);
Square s = new Square(side = 5);
Console.WriteLine($"The Paint required for the Circle: {CalculatePaintAmount(c)}");
}
}
this is showing the error Top-level statements must precede namespace and type declarations.
it is updating an existing shootOrigin variable
but the GameObject is not a transform,
yeah you can't have a random function like that outside of a class
i cant search only a Transform,
Because it can't. A function needs to be in a class
i didn't know that
it's extremely simple to get between the GameObject and the Transform
this only work because i search a Component
this time i only want search a GameObject
What does any of that have to do with anything?
You're going from the Component to the GameObject here already anyway
{
if (shootOrigin == null)
{
shootOrigin = GetComponentsInChildren<Transform>().FirstOrDefault(c => c.name == "ShootOrigin");
}
} ``` u said i should look at this method
yes the relevant part is that you're doing shootOrigin = something;
which is not happening at all in your other function
If you're going to be using incredibly slow find methods at least don't do whatever this shit is and just use Transform.find
why slow?
Get component is slow. Linq is slow. You're getting way more results than you'll ever need and throwing them out which causes garbage collection which is slow.
so what should i use?
Find is still slow but it's way better than this mess
The thing I've linked you like four times already
okay i will read it
is linq bad? i saw it on the Internet i thought this would be good
and why does it exesit if its slow?
You should really just assign the reference in the inspector directly
that's the best practice
i do, just wantet do make s safe call
Doing nothing is always faster than doing something. There's literally no point to using linq here. Why get way too much data then filter it down when you could just get the data you want from the get-go
okay, i will do that in the future
thanks @wintry quarry @polar acorn
for u help didnt know that
HAHA u also right i dint use the Method for the Shoot
thank u
tuff
@scarlet pasture yo are you the ytuber?
What youtuber?
there's a ytuber called BadGameDev
was wondering if he was him or someone entirely different
Til get component is slow :/ is there a recommended way when instaniating an object? (Say a bullet that you want to add values in when spawned)
Assign it in the inspector
If you're spawning a prefab, spawn it as the component you want to get
Well how would i do that during runtime
Get it from something that does have the reference
Wouldn't that in the end require at least one get component call?
Where?
You spawn the object, set whatever references it needs from the thing that spawned it
If other things need to know about the object that was spawned, you pass those references to those
you can assign a component reference in the inspector and pass that to Instantiate which will then copy the entire gameobject and also return the same type of component that was initially passed to the method like so:
[SerializeField] private MyComponent _prefab;
//in some method:
MyComponent instance = Instantiate(_prefab);
instance.InitializationMethod(data);
instance.someField = otherData;
calling instantiate on a class spawns an object with that class?
Calling instantiate on a reference to a component spawns the whole object and returns that component
you can pass any component to Instantiate and it will clone the entire gameobject that component is on like i said
Oh i see
Yeah my bad miss understood, but MyComponent would be the class right?
that would be the class that inherits from Component, yes
it's not just any class that works like that, because you can't just have any class attached to a gameobject (and also can only pass UnityEngine.Objects to Instantiate), it must be a component
So a monobehaviour or is there a difference?
MonoBehaviour inherits from Component
but it's not just MonoBehaviours that you can do this with because it's any component. Including things like Rigidbody which inherit directly from Component and not from MonoBehaviour
Right, well good to know ty.
helll nah, im just a bad dev
lol didnt know that a youtube exist with this name. but he makes great videos tbh
Oh I see. Same here
hahah
So when we get raycast hit normals, let's say we walk on a slope, the normal will be equal to the slope angle, correct?
It'd be the normal of the surface the raycast hit
how normal
Okay yeah so a normal on a slope would be the angle of the slope, or at the very least the angle of the part you're on
It'd be the vector pointing directly away from the surface the ray hits
angles are not involved
It's a direction vector, not a rotation vector
Oh okay
Nope
If you want to find the angle between 2 vectors you take the quotient of the dot product and their magnitudes and then take the arccos of that
There's a convenience method that does all that for you at least:
https://docs.unity3d.com/ScriptReference/Vector3.Angle.html
Or that lol
Hi guys I am at the point in my game where I want to create boss enemies (2D bullet hell type of game) and in these types of games sometimes or most of the time bosses have attack indicators like where they gonna use an explosion and how much time it will take for it to explode , like the indicators for bosses in MMORPGS , how do I create those indicators I cannot find useful resources online
Are you asking from a game-design standpoint?
For programming one, you'd generally want some kind visual representation of an attack. Some game use a disk that slowly fills into a circle when the attack is executed, so let's use that an as example.
You'd summon one of these either in UI or world-space depending on desired visuals/behaviour, and initiate them with parameters regarding attack size, delay, etc.
then handle the visual's appearance from another script that updates it accordingly with the parameter of time or something.
There's a ton of ways to do it though, so this question seems extremely open-ended.
`using System;
using UnityEngine;
public static class NewMonoBehaviourScript : MonoBehaviour
{
#region - Player -
[Serializable]
public class PlayerSettingsModel
{
[Header("View Settings")]
public float ViewXSensitivity;
public float ViewYSensitivity;
public bool ViewXInverted;
public bool ViewYInverted;
}
#endregion
}`
@polar acorn
three back ticks, not just one. and you need a variable of that type
what's the issue here?
yo that region is a little too small to need one no?
oh yeah that too
what do i need to change in the code?
You need to not have a static class that is trying to extend monobehaviour
Either it shouldn't be static or it shouldn't be a monobehaviour
so i should remove either one of them right?
remove either the static keyword or : Monobehaviour.
Removing either one changes the whole thing
i removed mono
it fixed the issue
thanks
now you've got a static class. As long as that's what you want you're golden.
It'll compile now but I've still got no idea what you're actually trying to do with this
yeah, making it both static and Monobehaviour suggests some shenanigans might be happening
NewMonoBehaviourScript.PlayerSettingsModel ?
It suggests a lack of understanding as to what either of those concepts mean
Yeah exactly the circle filling up example I am trying to do something similar , is there any tutorials I can check out for something similar
any "circular progress bar" would probably do
oh ok ok i see
so basically i just make a UI effect that goes ups
up
and when it finishes it summons an explosion
thats just visuals representing whats going on with a number you increase, basically sounds like you want a timer
yeah
mhm make the timer first, then you simply map that to the ui
yee i got the general idea
i guess i will finish my first boss first and after that attach the indicators after all its spells and mechanics are ready
I'm getting more of these errors?
no point in looking how to do it before the enemy itself is not 100% ready
Are you missing a using directive or assembly reference ?
!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.
why is that defined inside a static class?
can someone explain the Liskov substitution principle part of the level up your code book. I can't understand what it means
i didn't understand
oh! this is liskov substitution!
I sent that to someone else
I asked you why did you define that class inside a static class?
so i'm not supposed to?
well first of all if you waned to refrence that class its nested inside so it would be
src_Models.PlayerSettingsModel playerSettings not PlayerSettingsModel playerSettings
it's just a bunch of overriding bruh
What were you hoping to achieve by doing so
..I mean its part of it, but the point they are trying to drive home is that you should plan the Inheritance classes in that way
@rich adder another thing, wouldn't using an abstract class and an abstract method be better in the long run?
usually there is no "better" in development, everything has its own pros and cons
i guess i will need to figure this stuff out later on then...
abstract has its own limitations, where interfaces are similar but could offer better benefits in some cases
ya, i ain't gonna ask what does that mean
when you inherit the abstract class, you have to implement the methods inside of it
yes
which is very similar to how interfaces work
oh
except interfaces cannot have fields but abstracts can . etc
but inheritance is not always the best because you're constrained to the base class no matter what , so interfaces offer more modular approach
this kinda worked
but now have a new error
That error is self explanatory
this has nothing to do with the code itself but unity specific
oh?
The variable cameraHolder of scr_CharacterController has not been assigned. You probably need to assign the cameraHolder variable of the scr_CharacterController script in the inspector.
cameraHolder is not assigned
do you know what assignment means?
yes
okay so assign it , the second line gives you a hint to how
a very basic example where interfaces fit a situation bettercs public abstract class DamageableBase { public abstract void TakeDamage(int amount); } //error because we cant inherit multiple classes public class Player : MonoBehaviour, DamageableBase { }
instead of
public interface IDamageable {
void TakeDamage(int amount);
}
public interface IHealable {
void Heal(int amount);
}
//we can have as many interfaces as we need
public class Player : MonoBehaviour, IDamageable, IHealable {
public int health = 100;
public void TakeDamage(int amount) {
health -= amount;
Debug.Log("Player took " + amount + " damage. Health: " + health);
etc..
nvm i don't know how
i always keep running into errors
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hey, does sombody knwos how to detect the raycast distance is to short?
detect the raycast distance is to short?
what do you mean, what do you want to do exactly ?
if i were to say you could still kinda do it by using inheritance over and over again?
If your raycast is too short, make it longer
{
if (shootOrigin == null) return;
dir = PlayerMovement2DScriptRef.facingRight ? Vector2.right : Vector2.left;
RaycastHit2D hit = Physics2D.Raycast(shootOrigin.transform.position, dir, shootMaxDistance, EnemyLayer);
if (hit.collider != null)
{
//VFX Spawnen
StartCoroutine(VFXManagerScriptRef.SPAWN_ShootDust());
this.VFX_ShootDust.transform.position = this.shootOrigin.transform.position;
}
else
{
Vector2 endPos =
}
} ``` i try it many times but it dont work, i try to spawn at the end of the ray a bullet, so the Player know "AHH i need to upgrade my wepon"
sorry, i didnt give u all the needed Information
this is my Problem.
you want to spawn the bullet at the end of the ray ?
why not at shoot origin..
YEA! exactly, so the Player know his distance is to bad
i do, the dust say the player "i Shooted" so if the enemy in the distance he get killed but is the enemy to far away the bulletr soawn and falls to the Ground, so the player knows he didnt hit a enemy
do u understand what i mean?
kinda...but if you want the max distance as a position You could make the Ray struct and do ray.GetPoint(shootMaxDistance) ?
The end position of a raycast is the start position plus the direction times the distance
is this an instance of function prototyping?
ah yea forgot about that too
much simpler
shootOrigin + dir * maxDist
instance of function ?
nav how would u do that? i mean i have the feeling the spawning a bullet at the end seem kinda dumb
sry, is this function prototyping?
not the c# instance but like, english instance
is this an example of ...
still not sure what you mean by function prototyping
its not dumb but very unusual and probably there's a better way to do it lol
functions can't exist without a type in here
I have no idea what you mean by "function prototyping" but it seems like a pretty decent encapsulation of polymorphism.
i think i just play a sound and blood if he hits somone, this would look better at soawnign just a random bullet at the end
The "Interactable interface" is usually the go-to example of how to utilize it in a game development sense
it's just a term in cpp....
if you want to portray a MISS just make it not hit the enemy lol
hahahaha
u right
but know i need how to see the end distance of the ray. im sure i will need that in the future
you can define functions in there without actually coding what it does and then just write it in a later part of the code for the compiler to find out at compile time
what like header files ?
int add(int x, int y);
int main(){
return add(3, 4);
}
int add(int x, int y){
return x + y;
}
you define it beforehand, but write it anywhere other than the main block of code which uses it
That sounds incredibly annoying
here's the thing, am i stupid or is it that the level up your code ebook is not beginner level stuff to start with unity?
it's talking about concepts i have never encountered...and i am supposed to understand the context somehow?
I wouldnt say that, imo level up your code ebook assumes you already been coding a while
oh no
or at least know the very basics of c#
oh
differences between abstract classes, interfaces etc.. it assumes you kinda familiar with these but shows HOW they can make you write more SOLID patterns
Can somebody pretty please help me make a game? It’s called whispering apes
!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**
do you think it would be better for me to dive headfirst into making a shitty game first and then read the ebook?
it's not that i can't understand what most of it means, i just don't feel any connection to these subjects cus they are all very abstract concepts for me rn
I think in the beginning you should not be worrying about these but keep them in mind / slowly refresh into it later on
its okay to write shit code, thats how we learn
this way you better understand WHY we want to use these patterns
ya...that's what i wanted to know
you cannot see a benefit if you don't do it wrong first
aight, i will try following a tutorial for a game or smth then
can you suggest one?
2d if possible
also, not outdated unity
there's plenty of stuff on the Learn site
lemme check it out then, i will ping you back if i find one
check the stuff pinned too
the pathway is a nogo, my net connection is dog
how will you able to learn elsewhere then lol
just a problem with videos i guess. i can read though
i can check videos well enough on other sites, it's just a problem for unity
someone did tell me it could be because of my shitty ISP or smth
im sure you can probably find more text based tutorials all around
to learn I'd start with a very basic project, very minimal graphics. not much logic.
something like flappy bird and such
i know that, i couldn't find guides that's why i asked...
i did kinda make a few games on pygame so i know basic is the way to go at first
yeah cause you have to basically learn two things at once..
You have concepts specific to general c#, and then you mix that in with unity specific concepts (Components, GameObjects, Monobehaviors, Mono Events)
and the manual / docs has really good info
https://learn.unity.com/project/2d-game-kit is this aight?
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
or is it outdated?
I mean nothing really is outdated in sense, not much changed in the past 7+ years
ya...it is outdated
maybe some UI
problem is that i can't end up finding stuff
and very specific API changes, like rigidbody.velocity vs linearVelocity
that's a diff headache altogether
imagine trying to learn what stuff and then spending an hour trying to find the right stuff
the reason I say Learn pathways is they usually introduce you to the basic concepts
if not lookup 1 thing at a time then..
"how to move an object in unity" also works if you wanna go that route etc.
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
How should i do menus? I have an idea how to do so with 1 category (like screen -> screen resolution, window type) but what should i do if there's more categories, just make multiple panels and disable every but selected one?
depends how the UI layout is gonna look. I usually toggle a gameobject Active false/true
Thank you
What i normally do aswell, though ive heard keeping every ui object on the same canvas? (forgot its name might not be that) is bad
it is a good idea to split certain UI to different canvases yes, aside from organization there is a slight optimization there
every time you change something on canvas it has to redraw everything, so if you have more static items that don't need to be refreshed they should not be on the same canvas that say needs to make a change often and so on
eg. Dont mix healthbars with settings UI etc.
Redraw everything in that tree, up to hitting a canvas. It doesnt redraw the entire UI ..iirc
ahh dang its been a while I gotta find that video it was pretty old Unite or GDC I saw it on, probably unite where they talked about canvases thing
Unite 2017, top 10 tips for UI optimisation or something
ayee an OG Unity dev ^ 😄
A v.useful and informative talk , one I've watched many times
ya it was really good, I wonder if that stuff is still the same or they optmized it a bit
also never fully tried UIToolkit for game, i wonder the benefits there
There's also this page (which I think says most of the same topics). First thing it says is the entire canvas is dirtied.. I think you were right
ah okay good my memory still workin.. lol yeah I recall something like that , at the time I was basically making a lot 2D games on canvases
(mainly like card game and stuff)
so much easier to deal with scaling resolutions. no physics or anything
im trying to write a Foliage shader, like that supports wind. Is this the right place?
I made one but it doesnt have shadows.
okay thanks
using UnityEngine;
using UnityEngine.InputSystem;
public class clickhandler : MonoBehaviour
{
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector2 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPos, Vector2.zero);
if (hit.collider != null)
{
Debug.Log("Clicked" + worldPos);
}
}
}
}
I made this script to print the locations to where I click, when I put the script inside of the map and run the game, this happens
!input
To set Active Input Handling, go to:
Project Settings > Player > Active Input Handling
• Input Manager (Old): Use the original Input settings.
• Input System Package (New): Uses the new input system package.
• Both: Use both systems.
Hey, i wanted to ask. if i shoot a raycast? can ui get the Components of my Enemys?
You can perform a physics raycast, get some component from what you hit and then do something with this (such as display information in some UI somewhere)
If you are comfortable with the basics of unity this should make sense.
I Mean i use this => ``` private void Shoot()
{
if (shootOrigin == null) return;
dir = PlayerMovement2DScriptRef.facingRight ? Vector2.right : Vector2.left;
currentBullet--;
RaycastHit2D hit = Physics2D.Raycast(shootOrigin.transform.position, dir, shootMaxDistance, EnemyLayer);
if (hit.collider != null)
{
//Treffer
this.VFX_ShootDust.transform.position = this.shootOrigin.transform.position;
LocalSoundManagerScriptRef.PLAY_Miss(1);
}
}```
can i just say => hit.collider.GetComponenty<BaseHealthManager>(); , beacuse u said "get some component from what you hit and then do something with this". Did i understand u correctly?
physics 2d raycasts only hit 2d colliders so unless you put some on some world space UI then no
if(hit.collider.TryGetComponent(out YourEnemy enemy)) enemy.DooStuff()
sorry what do you actually want to know 😆
TryGetComponent? would it be false if i only said => GetComponent?
i just wanted to know, can i aces a component from a gameobject via raycast
but know i know it
its the same thing, but you would want a null check otherwise if you hit somehow an enemyLayer collider with no Enemy component you could get a null reference
Ofcourse
you know what gameobject was hit, therefore you can do normal things with this gameobject
such as... get components!
ahhh i do this every time => if (!CameraFollow2DScriptRef) CameraFollow2DScriptRef = GameObject.FindGameObjectWithTag("MainCamera")?.GetComponent<CameraFollow2D>();its the same with TryGet...
yeah i know finnaly understand it
Unity doesn't support ? on unity Object (components are UnityEngine.Object)
Thanks, didnt know that
so only on GameObject i cant say ?
not
anything Unity that inherits UnityEngine.Object so gameobject is one of them
btw you can do Camera.main to get the current main camera
ahh so i dont need to search the Tag Enymore
No
thanks didnt know that all
and sorry for my bad englisch. im Currently working on it
just make sure the camera does indeed have MainCamera as the tag
mhm just incase you make other scenes / brand new cameras
Different enough that C# doesn't suck.
Similar enough you can probably use both if you know either.
ah thanks
Hey, i wanted to ask. Why cant i reference a Transform from the Scene?. I try to say to my Script "Hey u need to take the "ChemberBulletOrigin" in the Scene"
but every time i try there is "Type missmatch"
i guess i need to search my Transforms in Runtime?
Prefabs cannot reference objects in the scene. You will need to set that reference after spawning an instance of the prefab.
i understand, so if i catch it in the Awake call? and the Player would move... would Unity register the new Positions? i did it now lilke that => ``` void Awake()
{
if (!playerMovement2DScriptRef) playerMovement2DScriptRef = GameObject.FindGameObjectWithTag("Player")?.GetComponent<PlayerMovement2D>();
if (!ChemberOrigin)
{
// Spieler suchen
var player = GameObject.FindGameObjectWithTag("Player");
if (player)
{
ChemberOrigin = player.transform.Find("---Combat---/ChemberOrigin");
}
}
}```
i didnt test it out, but maybe u know the answer
didnt we tell you about ? earlier?
yeah i thught i can use it but only if i search a Gameobject i cant search it
er sorry say again?
okay sorry
wait
i need to think
i thouhgt u said to me, i cant use ? if i search a "GameObject". in my case i searched the ScriptReferences. That would be fine?
you should do this:
MyCoolScript coolScript = FindFirstObjectByType<MyCoolScript>();
if(coolScript != null)
//stuff
find and store in a variable
then check if its null or not
rob why cant i use ? it works in the Game?
? is incompatible with special unity overrides so is not safe to use with gameobjects/components/assets
It works but there are situations where it will not work
Much easier for a beginner to avoid using it due to this
Trust us
i do, i will know use u method. is u like the same? but safier?
FindFirstObjectByType will allow you to capture the component at runtime
this is what i need
right so you can store it and then do whatever
and if i do this in Awake, and the Player moves. would Unity register the new Positions?
if the reference is the same, it will always be the same object
NICE!#
so now i only need to referenc with the new Method rob gived me and use it for the Bullets shoot remaining
yeah i know some of u said it would cost alot of performance
yes, because it scans all your objects
if its something that is being spawned though in most cases people pass the references through a method
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
One last Quastion, i understand that robs method is better, i try it like "how i currently know the thinks" i did it like that => if (!ChemberOrigin) { // Spieler suchen var player = GameObject.FindGameObjectWithTag("Player"); if (player) { ChemberOrigin = player.transform.Find("---Combat---/ChemberOrigin"); } } nav just of interests. would that work?
what are you trying to do here
ChemberOrigin = player.transform.Find("---Combat---/ChemberOrigin");
like in Roblox Studio, i navigate throught the Objects
dont use find method like that especially string versions
because i can change the name in the Editor? right?
and then it would crash. i hat that experience also in Roblox
you will catch a null refrence it wont crash
but my Game frezzes of a null references
correct because "Pause on Error" is toggled
💡 Try to avoid using any kind of Find() and make use of serialized variables. You can also maually setup and provide dependencies to spawned objects to avoid Finds!
i will try it
you pretty much never need to use GameObject as a return type in 99% of the time
well for example..
GameObject.FindGameObjectWithTag("Player");
this returns a GameObject
not very useful
ahhhh i know what u mean
more useful to just grab the component you want directly
if you wanna find the player, and we assume it has a Player script on it (aka a component)
Player player
you use player = FindFirstObjectByType<Player>();
then in Player you can store whatever else you want
okay, i ask u then, u definettly better than me. i give my Prefab a Script that gives him a random force to the right and left. but i need to Instantiate it from the Weapon Chember
how would u do that, so i know it in the future, and the Transform Spawn Position lies on the Scene
you mean through Instantiate ? because you can already have that reference in whatever is instantiating it
yeah i instantiae the Bullet use his Rigidbody but i also need to find the Transform positon in the Scene. What is a "universall" use of case to find References in the Scene via Runtime
{
ChemberOrigin = FindFirstObjectByType<Transform>();
if(ChemberOrigin != null)
//stuff
}``` because this would not work
because this will just grab the First Transform it findss..
yeah, i need to filter it down to the Name of the gameObject?
You need to provide your setup / explain it better
what is Chamber origin?
lets say its a Bullet prefab
BulletScript bulletInstance = Instantiate(bulletPrefab, barrel.position, Quaternion.identity)
bulletInstance.DoOtherStuff()
okay this i have currently also
your Gun spawns it or whatevr already has the barrel referenced as a transform
exactlly i use a Origin pos also but unity dont find "barrel" because it is in the Scene
and the Script is in the Prefab, in the Project Folder
so i need to search it throught Awake. so i used that
{
ChemberOrigin = FindFirstObjectByType<Transform>();
if(ChemberOrigin != null)
//stuff
}```
wait before you keep posting the same code
can you show what your setup looks like
like in the scene
FindFirstObjectByType<Transform>(); this wont do anything useful because all gameobjects have a Transform
my Scene
its good to use when we know a script WE made has only 1 instance
my bullet
ok now where is the object that spawns it
why does the bullet have to care about chamber origin
because it need to spawn at the right weapon position
then make the script that spawns the bullet hold that reference
not the bullet
you're doing it backwards
i do => ```? using UnityEngine;
public class BulletChemberLogic : MonoBehaviour
{
[Header("References")]
[SerializeField] private PlayerMovement2D playerMovement2DScriptRef;
[Header("Bullet Chember Ref")]
[SerializeField] private GameObject bulletPrefab_001;
[Header("Bullet 001 Settings")]
[SerializeField] private Transform ChemberOrigin;
[SerializeField] private float upwardsRandomness = 2f;
[SerializeField] private float torqueRandomness = 2f;
[SerializeField] private float shootForce = 15f;
void Awake()
{
if (!playerMovement2DScriptRef) playerMovement2DScriptRef = GameObject.FindGameObjectWithTag("Player")?.GetComponent<PlayerMovement2D>();
if (!ChemberOrigin)
{
ChemberOrigin = FindFirstObjectByType<Transform>();
if(ChemberOrigin != null)
//stuff
}
}
public void SPAWN_Bullet001(float DestroyAfter)
{
ChemberOrigin = transform.Find("Player/---Combat---/ChemberOrigin");
if (!bulletPrefab_001 || playerMovement2DScriptRef == null || ChemberOrigin == null) return;
GameObject bullet = Instantiate(bulletPrefab_001, ChemberOrigin.position, Quaternion.identity);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
if (!rb) return;
Vector2 dir = playerMovement2DScriptRef.facingRight ? Vector2.right : Vector2.left;
float randomUp = Random.Range(-upwardsRandomness, upwardsRandomness);
Vector2 force = (dir + Vector2.up * randomUp).normalized * shootForce;
rb.AddForce(force, ForceMode2D.Impulse);
float randomTorque = Random.Range(-torqueRandomness, torqueRandomness);
rb.AddTorque(randomTorque, ForceMode2D.Impulse);
Destroy(bullet, DestroyAfter);
}
}```
jesus
just make a Transfrom field in this script
public Transform chamberOrigin
assign it in the inspector
did, but i cant use it because this Script lies in the Prefab
prefab cant get references to the Scene
this script is not in the scene ?
no its in the Project folder for the Bullet
so this is the bullet script ?
ja
these names are confusing af
i mean yeah
why is the bullet spawning itself
? is that not normal
no lol
you dont have like a Weapon script ?
something that actually spawns projectiles on the player
yeah! and i want to use the public method from the bullet code
to instantiuate the bullets in the right moment
where is the weapon script
📃 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.
this is why proper naming is important lol
A tool for sharing your source code with the world!
look this is my Combat Script, i want to Instantite Bullets in the Right Moment, but currently i dont know how to find the right TransformOrigin in the Scene
dayumn this all is hard
this is the most over engineered script I've seen in a while
i can barely tell whats going on
really? i coded it my self beside of the #if Unity Editor
So you have a ray to shoot but then want to spawn a bullet?
a bullet that flys to the sky, like u would shoot with a gun and the bullet is Emphty now and flys to the ground
u understand what i mean?
wait so u mean that is not good?
could be better tbh..
its fine dw. Im just trying to understand it
what does linq have to do with anything here lol
i mean findinf the Spawn Position of the bullet
my only problem is that
i dont find the pos via runtime
brother.. I understand what you want, I just dont understand why you are doing it a certain way
thats why Im trying to understand what the bullet needs to do and why you are not directly spawning and setting position from this combat script
its hard to give a solution without understanding the full usecase / context
for me it does alot of sense, i have a prefab, a Script thats under the Prefabs. in that Script a public method that Manage diffrent bullets in my Game (this is why its calle bullet_001) and know my Goofy ahh Combat Script should Spawnt the right Bullets
yeah, but it would be clean
i try to make everthing in Methods
i heard that is a good practies
if i ever need to change somthing i know "Okay just go the the Method and change it"
methods isnt the issue
Bullet is a prefab, you want to spawn the prefab from the Combat script , Assign the barrel position from there
the language barrier is probably causing some misunderstanding
ofrcorse
so u want tell me its better to spawn it in the Combat Script?
of course
but i want alot of bullets and costum settings
i drew some tiles in a 2d scene then dropped in a couple prefabs but the tiles are aligned to the center of grid cells while the prefabs are aligned to the corner of the grid cells. how do i make both tiles and prefabs align the same?
thats irrelevant to how you spawn them
is this a code question ?
i mean if i had 5 Bullets, and i would diffrent Settings for each one, i would need to make 5 Methods... in Combat Script
why is that.. no you just pass whatever settings you want to the instance..
what exactly do you mean with "different settings"
ah i guess not haha
Damage, Speed, penitration, FireAmo
okay good. now You can passs those as arguements
let me make a quick example
yeah pls
public class Bullet : MonoBehaviour
{
[SerializeField] Rigidbody rb;
public int Damage;
public int Speed;
public bool FireBullet;
public void InitBullet(Vector3 shootDir, int damage, int speed, bool fireBullet)
{
rb.AddForce(shootDir * speed, ForceMode.Impulse);
Damage = damage;
FireBullet = fireBullet;
}
}
public class WeaponScript : MonoBehaviour
{
[SerializeField] Bullet bulletPrefab;
[SerializeField] Transform shootOrigin;
void Update()
{
//lets assume we press the input to shoo
{
var bullet = Instantiate(bulletPrefab, shootOrigin.position, Quaternion.identity);
bullet.InitBullet(Vector3.right, 12, 10, true);
}
}
}```
not though?
you're inside of bullet script looking for origin of barrel..
bullet should not care about any of that..
is that not the same like my => and thant spawning the method in the CombatScript?
bro im to dumb
and yess i will change the ?
no becuase you're literally looking stuff from the bullet when it can just passed from the Spawner
and most of that shit is not needed..
its an expression I dont mean literally
"stuff" whatever
why does Bullet need to search the player for the facing direction?
you see my example you can pass the direction directly when you spawn it ?
yeah, if the player looks left the bulletr should come right out
so how's that i want to have it random
its not random if its based on where player is facing lol
make a thread btw so we dont flood this chat
i dont know man, my code is hella chopped
i just do somthing
hoping for the best
I think you overcomplicated it , thats all.. very easy to do in the beginning and even with experience
simplify it, make it easier on yourself
okay, so im try to make it easier, i just delete the bullet Code, spawning the Bullets from the Chember in the COmbat Script?
look at my example
Combat Script spawns the Bullet and sets all its settings..
Bullet script just handles getting that info and execute it, it DOES NOT search for anything
anyway, if you wanna keep discussing it further I'll help where I can but make a thread so we dont flood the chat
okay, u the expericend man. i will just use u example thats it
we can close this dicussin, nav really thank u for u timr
np.
use the example as Base, no need to copy line by line.
Quick question:
Wondering how i might compare the rotation of an object to that of an approaching object
Trying to check if the incoming objects movement direction is parallel to the stationary one's rotation.
For context image a runway, and checking if a plane is parallel to the runway or is it not.
im trying to snap a gameobject to the grid using this code:
{
float offset = 0.5f;
Vector3 rounded = new Vector3(
Mathf.Round(transform.position.x),
Mathf.Round(transform.position.y),
0f
);
Vector3 snapped = rounded + new Vector3(offset, offset, 0f);
rb.MovePosition(snapped);
blockBounds.center = snapped; // Update for next time
}```
But since the gameobjects pivot is at its center, i tried adding a 0.5f offset, but now it doesnt snap to the correct grid position. it IS offset but just not the right grid position. maybe its got something to do with my other code?
you can use Dot product
how are your grid cells defined?
i guess you can compare with Transform.up (or right/forward)
Vector3.Angle also works
not sure, im new to unity
and then yes use the dot product
do you do like (0, 0) (1, 0) (2, 0) 🤔
i mean the basic grid inside the scene view
oh
i mean i imagine different gameobjects would have different sizes so different amounts you'd have to offset them by
tho i don't see why not just use a Grid component
this is what it looks like
everything is aligned there
but when i move the red squares (the prefab) they snap to the middle of grid slots
nav i did what u mean
is it an editor tool?
it finally work
yeah but i did a own simpler methode
KISS?
keep it simple silly
KISS, an acronym for "Keep it simple, stupid!", is a design principle first noted by the U.S. Navy in 1960. First seen partly in American English by at least 1938, KISS implies that simplicity should be a design goal. The phrase has been associated with aircraft engineer Kelly Johnson. The term "KISS principle" was in popular use by 1970. Variat...
Okay i looked that up but not quite sure how to apply that
So im comparing the dot product of both vectors?
If its zero, they are parallel?
but what if i wanted it to be within 5 degrees of being parallel
the dot product is a way of comparing (ish) two vectors
if both vectors are normalized (i.e. length 1), then the dot product will be 1 when they're pointing in the same direction, 0 when they're perpendicular and -1 when they're pointing in opposite directions
some like this
float minThreshold = 0.95f;
Vector3 runwayDir = runway.forward.normalized;
Vector3 planeDir = airplane.velocity.normalized;
float similarity = Vector3.Dot(runwayDir, planeDir);
if (Mathf.Abs(similarity) > minThreshold)
Debug.Log("Plane is parallel to the runway!");
else
Debug.Log("Plane is NOT parallel.");```
assuming your runway points Forward
how do u even know that all wtf
having to use it for many years lol
If you understand Dot product and unity its easy
did u every maked a commercial game?
they are really handy, like if you need to know if a player is sneaking behind an enemy and perform a Sneak Kill etc.
unity is hella hard
but i think the hardest part is drawing tbh
Dot product is a math function, I actually only officially learned it because of untiy
my school math was not very good lol
once i put all the school math into unity it made more sense for me, I learn that way :p
theres a lot of people who know what for loops are but dont know what a sum operator is
even though its practically the same thing
yeah i was talking about this the other day with a Freira tweet I found
yeah exactly
i got statistics in college and knowing this litterally saved me* lol
big scary math symbols
sigma
I can do nested loops (multi dimensional arrays etc.) but then I see those real math symbols and I'm suddenly getting humbled rq
its such a wildly different application of math
that sometimes you dont even realized how much of math you know
because you learned learning to develop
its great because its self teaching through practical effort
some people just learn differently I suppose
I'm also more visual, I need to see whats happening visually to really "get it"
its great programming allows you to iterate easily and quickly
"shit i have another error time to open up another project"
Unity isn't capable of supporting VP9 videos on desktop platforms? I've heard about WebRTC, but I'm not sure if it's possible.
afaik it should (or maybe Im thinking in the editor)
why not just 
If that is what I will do for a few lost hours, they cleared my doubts.
Thank you for including the minThreshold part
I didnt understand that at all
Working beautifully
You will be in my credits
umm I'm looking at WebRTC and I see some logs that use TCP or UDP to stream video from the camera, could that be useful?
Don't think WebRTC is TCP
WebSockets is
But yeah (live) streaming stuff you would use WebRTC or any type of UDP usually
umm This WebRTC example refers to the VP9 codec
what is a vector chat
According to googl, "Vector Chat" is some random pointless LLM no one will ever care about or use
i set my thing to opera wwhen it asked what i wanted to code with and i pressed use this choice alwayse and opera doesnt work so i dont now how to fix it
!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
yes but how do i switch it i dont need a coder i need to switch it
You follow the guide for the one you want to use
Idk what you mean by "I don't need a coder"
Is "opera" some kind of new ide? I thought it was a browser. 😅
anything can be an IDE if your standards are low enough
Hi guys, so i have a .jpg file which contains several game icons. Then i use a sprite editor to split them into a single icon.
Now my problem is: how can i reference to a single icon by using Resources.Load()? i want to load a specific icon and stores the texture in a variable.
why not use serialized references
!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.
I need help with a issue, both spawners I have are going at the same time. I am not sure why, they should be going different times. Each one focusing on different things. I also wanted to see how I can make my code better, cause I know it's quite bad
A tool for sharing your source code with the world!
There's nothing in this code that would make them "go at different times"
What's the point of all these coroutines whose only yield instruction is another coroutine? These are identical to just normal functions
Well the timer for rarity spawn should change when the instantion. At least that what I thought would happen
I was thinking I need to split it up but now that you mention, I can put all in one I believe.
Right now you wait for 500 physics steps then call all your functions in a row
Where is it doing that at? Cause shouldn't both be separated since the for one Starts right away while the other is active through the update?
Sorry, didn't notice the one in start. The one in start runs, then 500 steps later it'll run another one. None of these coroutines have any sort of wait conditions, so they behave just like normal functions and run to completion when started
The basicObjectSpawner have a yield return new WaitForSeconds once active it will cycle through each time on what the spawn interval is. Which equals 10
Sorry 5
Ah, sorry, that pastebin site apparently doesn't work well on mobile, I searched for the function and it only showed the one in start, so I thought it wasn't included. Guess it only searches what's on screen for some reason?
Ah, strange. But yeah, i'm not sure why they both spawn at the same time
So, at the start you kick off a loop that'll spawn a basic thing every 5 seconds. You also have a countdown that will kick off one rare spawn every 10 seconds.
So, 5 seconds in, basic. 5 more seconds, basic and rare. 5 more seconds, basic. And so on
It should do that but the thing is. It does it once at the beginning then both spawn at the same time every ten seconds
Sounds like your spawn interval is set to 10
But I checked and your right but the number, it's set to five.
Is it set to 5 in the inspector as well?
Have you changed your fixed time step?
It was the inspector, never checked it
Thankyou
why does this not work
in fixed update
the only other lines of code are movement and it shouldnt affect this
what does it say
have you looked at the documentation page for AddForce online?
rb.addforce is no longer structured like that, id reccomend reading the documentation on it to learn how it works
then what do i use?
did you do this
ye
you still use rigidbody.add force, just read the documentation with the updated overloads
What's the difference between whats on that page's examples vs. yours?
🙂
it had x y z
you need that additional forcemode argument to explain how the force is done
if you click ForceMode's documentation it explains the options
you probably want force or impulse
the documentation explains the different forcemodes, pick the one that works best for what you want to do and just use that
what does it say
hold on
that is odd
ok so thats a rigidbody2d which works differently
nice
No worries
just a small nitpick/heads up btw, it having "4 arguments" isn't a reason why you shouldnt be getting that error, that just means for that Type it can't find a valid Function that matches those Parameters your trying to give with it
oh
As you've seen with the AddForce it has different ways you can give it information even though it's the same function. that error is just saying "hey whatever your chucking in here isn't something this function is built to handle"
i see
okay now
why cant i give it delta time
fixed it just gave fixed delta to the z value instead of the mode
2 quick things to note:
when dealing with rigidbodies and physics theres no need to multiply by delta time since unitys physics system does it for you
when you're dealing something NOT physics based (like the second part of your code that translates the object left and right based on input), it should go in update
mixing addforce with translate 🤔
it was just autofill from vs code
the movement works
as intended
im tryna find out whats tranform.translate
in the documentation
you're essentially teleporting
ae
those two things can cause issues down the line
Specifically, not doing the first one makes your physics calculations proportional to delta time squared instead of delta time, which can cause issue
Not doing the second one will make it so running the game on a higher framerate has no effect on input snappiness (i dont think thats the right word but you get the point)
translation on transform is skipping the physics so it could at some point phase through walls , colliders are physics
linearVelocity or AddForce , depending on feel
You can set the velocity directly
Doing the first one will feel more similar to translate if that’s what ur aiming for
addforce seems to fit
one thing to keep in mind is AddForce will keep increasing velocity
unless you set limit / clamp velocity
You'll need to clamp it to keep a set speed, and apply force in the opposite direction to stop . . .
if I want to make "chunks" for my single-scene world (it's not randomly generated chunks, only for loading/unloading parts of it): loading a prefab with all the stuff and enable/disable it after the first load - will it bite in my ass by huge RAM usage of disabled prefabs scattered around the world and I'm better unloading them completely instead of just disabling within some sort of pool?
if they all share similar resources then technically the cost is that of a gameobject/transform
- w/e component data that's unique to each object
larger issue is textures and model data usually
so holding them as disabled all the time is not very good, I suppose.
maybe I can use some sort of "inactivity timer" to unload prefab which is disabled for too long, lol. kinda convoluted solution, but maybe it will work nicely/okay-ish.
hey
I used LINQ yesterday to find components, and some people said it's a bad practice.
After researching, I found that since Unity 2022, LINQ performance has actually improved a lot — especially with IL2CPP and the Incremental Garbage Collector.
Using something like ```FirstOrDefault(l => l.name == "ShootLight");
The real issue only happens when you use LINQ inside Update() or FixedUpdate(), because it allocates memory every frame.
Still, I built a zero-alloc alternative for cases where performance really matters: ```ShootLight = FindUtil.FindInChildrenByName<Light2D>(this, "ShootLight", includeInactive: true);
``` This method uses the GetComponentsInChildren(includeInactive, List<T>) overload and reuses a static buffer list, so it creates no garbage.
So yeah — LINQ is not evil anymore, it just depends on where and how often you use it. 🙂
you are searching for something with a name which 99% of the time can be done a better way
Linq is best avoided and we tell this to beginners so they dont do crazy things when a simpler approach is better
😭😭😭
So okay I don’t use linq I understand that BUT u wanna tell me that my other method is also bad?
Atp im just quiting hahaha
Instead of spending time building elaborate machinery to find components by name, you should use that effort to fix the project code structure so that you don't need to find components that way
Make components and prefabs that already have references assigned and required logic ready to go
If you need a method to find components by name you're doing something wrong. There shouldn't ever be a need to find components by name
(Or usually anything by name and/or string)
And yeah linq is fine unless it’s in pretty heavy update loops
HOW???? i mean i want to use a light when the player shoots, the Light is a Child of the Player, i cant say "GetComponentInChildren", beacuse he would use the first Light he finds under the Player. But i have alot of Light. And also the Light never change the Name so why shouldnt i use a string?
I believe this was explained to you multiple times yesterday
Have a serialised field for the light and connect them in the inspector
im so proud of myself
[SerializeField] Light2D ShootLight and drag the light there, or if you can't do that, public Light2D ShootLight and the component that instantiates the thing will set the value
Yeah i understand that nav telled me that but i just wanted to create a Fallback, in case of somthing i forget or the Game cant find it for what ever reason
i didnt really understand HOW i can find a Spzifical Object in the Scene
That's a silly reason
u mean a dumb reason?
Well yes, if you want to put it bluntly
but why?
make it fail-fast
so you get an error explicitly telling you that you forgot to set a reference
you don't really need a fallback
"the Game cant find it for what ever reason" – this is not something that happens. If you assign the value correctly then it'll always work.
unity tells me that => Null references i dont need to do that with a log
If you expect the game to just randomly break, how can you be sure that your fallback doesn't also randomly break?
...yes, that's what im saying. thus, you don't need a fallback
Hey, how can I check if any of the mouse buttons other than scrollwheel are being held down here?
private static void OnSceneGUI(SceneView sceneView)
{
var e = Event.current;
if (e.type == EventType.ScrollWheel &&
e.button == 0 &&
e.modifiers == EventModifiers.None)
{
Zoom(e.delta.y);
e.Use();
}
}
e.button == 0 didn't work sadly.
The reason I wanna do this is when you hold right click, scroll is supposed to adjust the movement speed.
My script cancels that rn.
I agree with what others are saying but in the scenario you do need to do this, searching it can be easier to do it in reverse where the thing your trying to find instead loops up the chain for it’s owner
okay, i understand that know, i dont need to make the fallbacks.. okay. BUT can u tell me how to search a Spezifcal Object without a Tag. So i just know how to do that if i ever need that
ok imma be blunt. what you're thinking of is called "magic strings" and it's a pattern that should be avoided because it's very fragile and mistake-prone
you should never "need" that, period.
you should have better, more resilient, easier to work with systems in place
this is what serialized references achieves