#š»ācode-beginner
1 messages Ā· Page 709 of 1
Probably want to just install the whole 2d tools bundle
would it be possible to just change the renderer in a 2d project?
cause i have everything there
kk
Any tips on how best to make menus? Iām trying to use the built in button but I donāt know how they work and the docs arnt helping
Explain where you've gotten stuck. Other than that, pick and follow a tutorial
If it were 3D shouldn't the shadow get thiner in certain angles because of the sprite plane?
there's a bunch of tricks you can do and one of these is making shadowmap data from sprites pointing towards the directional light source and using that data on the main rendering
ssome easier solutions such as just offset the shadowing
Ah yes, I just watched the video, I'd bet on 3D too now
The game is beautiful by the way
Those artists are talented
i know, i want to do something similar so bad but its so complicated haha
Mostly in how the buttons work on the code side and how to do outputs
Wdym outputs?
Like get when the buttons is pressed
Buttons have inputs where they call a function when pushed
in the On Click () part of the button you can pick a Object and from there the drop down shows all components
Ok and you can make that be any function you want?
if you make a script then put it on one of those objects it'll be there
I thought you needed to do a special thing ljke how the input system worked where it needs to have InputAxtion.callbackContent content jist diffrent for the click
where you have different options inside each class all being functions these are base MonoBehaviour ones you can add your own functions to the script and they will show there
only thing is the function can't have special variables in the () only base values like a string, bool, int, enum
amm ok noted. i wastn really planning on having any but good to know
so (string Name) would work but (ClassThatDoesSomething Something) wouldn't
i think it's value types that work and reference that don't but i might be wrong since i don't mess with it enough
also is there a more effective way to have different parts of the pause menu than something like this where i need to enable and disable each section?
this is how i've got it
my current system is gonna be
if you click options disabel all but options
if you click restart disabel all but restart
ok i was wondering if there was a "right" way to but i guess this is a good method
I have an idea behind my menu and ima see if i can do it or not
How do you send messages from one script to another if the scripts are in different game objects?
get a reference to the script and call a function
usually you'd use GetComponent, make a singleton reference or just set it in the inspector
@timber tide i figured out how they did it if you were curious https://www.kickstarter.com/projects/81monkeys/world-of-anterra/posts/4127381
interesting idea
way over my skill level haha
I'd love a tutorial on how to build SOME and POGGERS
Learn how to handle references
does anybody know why this code its like causing to like continuously repeat the attack animation even though i want it to play only once
.code
.paste
yo whats that bot command called again i forgot
.easy.gg

š 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.
can anyone help me plz im new at coding why does it keep repeatedly playing the attack animation even though i want it to play only once and its a trigger? https://paste.mod.gg/basic/viewer/zsybobsclbyp/0
A tool for sharing your source code with the world!
Nothing to do with your code. Sounds like that's just how you set up your animator.
did i set this up correctly
same
well im following their official website tutorial
i like how they give u challenges and never give u the answer to the challenge
Im wanting to make a laser to connect show connections to the player. I see the Line Render but it doesn't seem to do what i want and i also wanna try and do dotted lines for when its off. What would be the best way to make this? I would also like to be able to make a list that connect them
line render probably most performative, and you can use a dotted texture, otherwise probably just init a bunch of circles like quads w/ texture
okay. How does it work? Is it a thing i need to sue largly with code?
Can i give the possitions gameobnjects or no?
Hiii guys
Hi
Awake is called when the gameobject becomes active
Start is called when the component becomes enabled (on the first frame that it is enabled)
Awake comes first
Most of the time tho (in my experience) they are interchangeable unless you have an object disabled at the start but needs to do a thing before hand
that "unless" is doing a lot of heavy lifting lmao
that's not really an uncommon situation
Couldn't you just use Start() and write out the things that should happen first be done first?
Or maybe the deactivated object depends on other scripts (?)
Awake and Start happen at completely different stages
sometimes you need to make something initialize before something else
So by default what should I use?
The rule of thumb is that you do internal initialization in Awake and everything that involves other objects in Start. That way you don't run into issues trying to access something that isn't initialized
oh okay makes sense
there is also OnEnable, btw.
Yeah usually Awake for stuff dealing with just itself and Start is when you leave the house and talk to others
The mindset of this is by the time Start happens things should be āreadyā (via Awake) for communicating
If your class needs a shower and morning coffee thats in awake
it first happens after Awake, but before Start, then anytime the component gets enabled (including the gameobjetc getting activated while the component is already enabled)
it's part of the component lifecycle
it's useful for doing initialization that may need to be redone after disabling or deactivating
OnEnable & OnDisable kinda feel like clocking in and out it work imo
Time for unity, lets see how it goes!
Wow Unity loads up fast, last time it took way longer lol
Depends on the project haha
My last Unity project was a tutorial I quit after the first episode not working lol
So where do I place my own config file that my project is gonna use? In the assets folder?
Wait, nvm I forgot I can set components of my camera
config for what?
Oh no I don't need it anymore, but it was for the camera scale size. Because my planets will be near real life size, I will have to scale them down by a factor(that'd be camera scale size or smth similar) to make unity render it properly
Like Kerbal Space Program does it
Is there any reason plugging a subsclass between a base class and a subclass make the subclass not behave as with only it inheriting from the base class?
I currently have
DragonfryController : EnemyBaseGround
and I want:
FlyingEnemy : EnemyBaseGround
DragonfryController : FlyingEnemy
however, even with "nothing" in the intermediate subclass FlyingEnemy
I get NullReferenceExceptions triggered by my Patrol() script (note that I don't get the issue with only EnemyBaseGround inheritance)
that's a very vague question
it sounds like you have other issues and you're looking at the wrong thing
https://xyproblem.info
perhaps share some !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.
Guys I'm getting this error:
transform.position assign attempt for 'Earth' is not valid. Input position is { NaN, NaN, NaN }.
UnityEngine.Transform:set_position (UnityEngine.Vector3)
Gravity:Update () (at Assets/Scripts/Physics/gravity.cs:33)
using UnityEngine;
public class Gravity : MonoBehaviour
{
public string type;
public double mass;
public Vector3 velocity;
public Vector3 position;
public GameObject[] planets; // array to hold planets
private double gravitational_constant = 6.67384e-11f;
void Start()
{
}
void Update()
{
if (type == "Planet")
{
foreach (GameObject planet in planets)
{
Gravity planet_gravity = planet.GetComponent<Gravity>();
float distance = Vector3.Distance(planet_gravity.position, position);
if (distance <= 0f | distance*distance <= 0f) continue;
double planet_mass = planet_gravity.mass;
double Force = gravitational_constant * ((mass * planet_mass) / (distance * distance));
double acceleration_magnitude = Force / mass;
Vector3 direction = (planet_gravity.position - position).normalized;
Vector3 acceleration = direction * (float)acceleration_magnitude;
velocity += acceleration * Time.deltaTime;
}
position += velocity * Time.deltaTime;
transform.position = position;
}
}
}
Why is it NaN?
Did you debug what numbers you are trying to assign?
no
Would the most straightfoward of getting the current position of the player Object would to use a vector3 and Find the Game Object tag Player so something like
var currentPlayerPosition = GameObject.FindGameObjectWithTag("Player").transform.position;
š¤
just create a direct reference to the target and get the position
[SerializeField] Transform player; // declared as class variable (at very top)
Vector3 pos = player.position; // in the update method
š¤¦š½āāļø just started all of this today so appreciate that.
How can I multiply all numbers in a vector 3 by a float?
Find methods are very slow and generally should only be used in debugging or perhaps in third party tools that have no other way of getting a direct reference.
example?
When you are working in a team and need to debug a variable without changing core code, so you temporarily get that variable through Find, so you won't forget and deploy PR/merge that changes core code.
Basically you never use it unless you really have to.
So basically Find Methods are normally just a temporary debugging type of thing is what I'm understanding.
It's a very slow way of getting a reference globally anywhere, which is already bad in itself. There are better ways
Ay, my planet is moving finally lol. But I need to rewrite their gravity code, ChatGPT screwed up big time...
It's a self inflicted injury.
Yeah
Gotcha, Appreciate it. No programming knowledge is showing clear as day but we're here for the long run
But tbh, I just wanted a solution, and I didn't know how to apply my acceleration to the velocity vector because I'm horrible at maths lol
Check https://unity.huh.how/references for "better ways"
And I didn't want to make seperate variables for x, y and z. But that's the way I'm gonna be doing it
and avoid using Find methods in the update, you can if you have to, use them once but don“t ever use them every frame
But the approach you showed earlier With Using SerializedField Can be use in update or is this considered a type of "find" š¤
Vector has no problem multiplying on a single number. You just need to check that are working with valid values/types in the first place,
i edited the code with comments for you, @Tyler
Yeah. I forgot to set mass to 10 on the Mun and that's why everthing was screwed up lol
it was 0 befor
Alright exactly what i just did then appreciate that.
do you also understand the wisdom behind it?
as a beginner it is really important to understand code and the way it works, especially in the beginning
Not exactly no.
well now instead of searching for the GameObject every frame you already have the reference (assigned via inspector) . now you just get the position of the object every frame
Which is due to the [SerializeField] correct?
yes , you manually assign the player to this field
So [SerializedField] Allowed it to be public to the inspector Transform is just stating the class we're wanting to use and assigning it to the player?
you could also use [SerializeField] GameObject player instead [SerializeField] Transform player
since you are interested in the Transform it would make sense to declare the Transform. otherwise you“d have to do player.transform.position
multiply them directly
you can just, do that
So [SerializedField] is making it visible to the inspector Transform is just including the class we're wanting to use and assigning it to the player
I"m tryna make since of this line by line so to speak
you aren't assigning anything to player in that line, you're declaring that player is of type Transform
gotcha that's what i was tryna make sense of.
Why can't I use force_x even though I declared it outside of the if statements
would you not have to parse the mass too
hover over the error to see what it says
I declared the mass earlier outside the if
only fields get default-initialized
it's not legal to use local variables that haven't been assigned to
(mine's in german so I'll translate)
Usecase of the not declared local variable "force_x"
Wdym not assigned to?
you sure? it's saying it's a local variable so it knows it's declared lol
it's more likely saying it's not defined
it hasn't been given a value
i was vague, mb
it hasn't definitely been given a value
if distance_x is <= 0, then it wouldn't be assigned to
Oh, so I'll just set it to 0 at the start
Thx
The earth realy accelerated the mun to 200m/s
Why calculate gravitational force in 3 floats?
Well, I'm too stupid to work with vectors to be honest
I mean I like it more this way
right but this is more effective since you only have to deal with one variable
Yeah propably, but idk tbh.
it propably is easier and smarter and more performant, but my CPU is beefy enough
it's not about the cpu :/ it's about the ease of writing the code, you wouldn't want to have to change something here months later to go crap wtf why did i go the easy way out and have to rewrite it all
Idk i guess it's preference though im not goonna go out of my way to force something you wouldn't like.
But you do have to multiply distance for each axis by itself here this is currently incorrect and leads to a miscalculation
Lol. But knowing myself, I will stop this project befor I can launch a simple rocket off a planet lol. But you're right. I'll propably come back tomorrow when the gravity isn't working for some reason and think why I did it that way lol. But eh, it's fine. I just don't have the motivation to do it tomorrow. Tomorrow I'm gonna make this way clearer making my own functions like applyaccekeration or converttoacceleration
btw, ignore the non existent underscores, but discords formatation is annoying
Oh right, thanks
that's why the earth was flying out of the system at a few thousand km/s
Should I use ScriptableObject to save the spawn point of collectibles in a 2D platfomer?
why not just save them on the object
Becuz I plan to have dozens of them spawned at pre-defined positions
Guys, why is the earth flying away when I start the game
Earth is at the handles, the mun is the tiny speck
Show the gravity script
Alright, wait a sec
Sorry, had to upload as a file @keen dew
!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!
force to acceleration doesn't involve time, the Time.deltaTime is technically wrong - it should be applied when turning the acceleration to velocity
Now even the mun is crazy far away lol
that shouldn't have made a difference...
this right?
yeah, it wouldve just been moving the calculation, not actually changing it
Befor i had it like this
this is the change im talking about
- float acceleration_x = (float)(force_x / mass) * Time.deltaTime;
- float acceleration_y = (float)(force_y / mass) * Time.deltaTime;
- float acceleration_z = (float)(force_z / mass) * Time.deltaTime;
+ float acceleration_x = (float)(force_x / mass);
+ float acceleration_y = (float)(force_y / mass);
+ float acceleration_z = (float)(force_z / mass);
- velocity += new Vector3(acceleration_x, acceleration_y, acceleration_z);
+ velocity += new Vector3(acceleration_x, acceleration_y, acceleration_z) * Time.deltaTime;
Ohh, thx
though just making this a Vector3 would probably simplify it...
It's still way too fast I think
also, you should have planets typed as Gravity instead of GameObject so you don't have to do GetComponent every frame
yeah, like i said, this wouldn't change behavior, this just makes stuff say what they actually are
if you're scaling stuff make sure to scale different values by appropriate amounts
i'd guess that your mass vs velocity vs distance are just off
Oh I'm so stupid
I have to set the position in the gravity variables, not the transform section lol
why not just use the transform position though
seems pretty unnecessary to store that a second time if they're going to be the same values
Since I want to scale up the planets to a realistic scale, and unity wont take those transform values well
you plan to move everything to doubles and do the math there then convert to float or something?
unity runs on floats anyways
I want to scale the whole solar system up or down, depending on the current scale_value
Since I want to actually scale the planets up to real size
The moving part in the transform is just for testing rn
you want to change the size of stuff at runtime?
yea
...why?
Kerbal Space Program does it too
As I explained, I want to scale up everything to real life scale
ok, but you can just do that once, and then keep that scale
why do you want to change it at runtime
I dont know
why not
For example: when I'm on a planet, I want higher resolution so I scale it up
because that seems really unnecessary to have to go through every object and change its scale and position and velocity and mass
that's pretty unrelated to scale.
you just use a higher resolution mesh for that
Well, if my planet is 1.0 size, the increments will be a bit higher than if it was 1000 or 2000
So the mesh can be more accurate ig
they don't seem to have significantly different ulps
the next number from 1 is 1.00000011920928955078
the next number from 1000 is 1000.00006103515625
are those.. supposedly micrometers, really that significant
i think you're thinking too far ahead. get something that works for now, before making it good
Yeah good point. I'll propably only scale them down when I first start the game. So I can still type in 40000km (radius of earth or smth) in the script and get the scaled down script. makes working with it easier
radius of earth is around 6000km, lol
40000 is circumference iirc
I'm sorry, i'm new here.
I have some animation trouble here, where can i ask about that?
Yeah could be that
in the #šāanimation channel, perhaps
Thank you!
I think I need to make my planets way, way slower
nah, you dont need a SO for that, you can have a Spawner with all the spawnpositions and even the objects you want.
Uhh, I'm gonna tip my toes into some ui. I can't watch this simulation for 1 hour just to see if i got an orbit
sorry to highjack onto that question, but I am using a struct for all my NPCs stats I.E. food, hunger, etc, would it make sense to use a scriptableobject in that case?
scriptable objects store base data, you should not store data you plan to change in there
stats such as max health, health regen, max hunger, inventory space can go in scriptableobjects
current state like current health, current hunger, what's actually in the inventory would be stored with monobehaviours (perhaps indirectly)
how I have it right now is a struct with the stats then in the Start I initialise them with their values, I have age, hunger, hungerthreshold, thirst, thirst threshold, and hasPartner, so for a SO i'd just have the hungerthreshold and thirst threshold really in it?
doesn't seem worth it in my specific case
SOs are very niche. You probably won't need them unless you're making inventory items
I guess i'd have model prefab too later on or something
ah okay, i'm not gonna have an inventory just having NPCs
Ok I get it. But saving tons of that data still seems like overkill. Is there a specific technique that ppl use?
If the data isn't associated with specific objects in the scene or any one particular object in the scene, you can opt for using SOs. Other than that if you're simply needing a container to store data that's okay with being associated with an object, you can simply populate serialized data from the inspector on the specific objects or some manager etc
It doesn't matter if it's in the form of a struct, class or a field member.
The bullets from my player are being spawned by using animation events. When my player moves and shoots at the same time, then the second bullet moves diagonally instead of straight upwards vertically.
public void ShootLeft()
{
Vector2 spawnPos = (Vector2)transform.position + new Vector2(-Mathf.Abs(positionOffset), 0f);
Instantiate(projectilePrefab, spawnPos, Quaternion.identity);
}
public void ShootRight()
{
Vector2 spawnPos = (Vector2)transform.position + new Vector2(Mathf.Abs(positionOffset), 0f);
Instantiate(projectilePrefab, spawnPos, Quaternion.identity);
}
The only difference is, that the spawn point on the x axis is the negative.
That is the script for the movement of the bullet.
private void Update()
{
if (Camera.main != null)
{
Vector2 viewportPos = Camera.main.WorldToViewportPoint(transform.position);
if (viewportPos.y > 1.1f) // Bullet is off the top of the screen
{
Destroy(gameObject);
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Obstacle"))
{
Destroy(gameObject);
}
}
And the question?
U are saying if multiple objects can share the same parameters, it is advised to use SO. Whereas if each object's parameters are unique, I'm better off with regular class. Am I understanding it correctly?
Why does it move diagonally instead of straight upwards?
I'm referring to associate as in where the object should live.
SO is practically a MB component that isn't associated (attached) with/to a Game Object.
With intended restrictions such as immutable etc
Hello everyone Iām making a third person shooter, so I have an enemyAI. By itself it works fine (basically perfect). But when I right click and duplicate it and move another one to another location. They both just break and almost sink into the ground. This is an annoying issue and some help would be useful
Nothing in any of this code moves anything
I don't see the bullet moving in the code provided.
You need to show us the code that moves the bullet
Not enough details here for anyone to be able to help
You need to debug your code
I can show you the code and what happens let me just get pictures
!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āll show you what happens when I press play too as thatās where the issue is
I have no clue where else it should be.
Yeah, but I just blindly followed a tutorial
How are you moving the bullet?
I think I found it
https://paste.mod.gg/basic/viewer/pdcluvauxity/0
Here is the enemy AI with the code I wil also provide screen shots with 1 enemy ai and then with 2. The second one is duplicated with the position just set a few units away from the other. With 1 it is perfeclty following me and shooting me like it is supposed to and then with 2. It just becomes whatver this is 
A tool for sharing your source code with the world!
private void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.linearVelocity = Vector2.up * 5f;
}
What you've shown is where you're spawning the bullet and how the bullet interacts on collision etc.
That is the whole script for the prefab
using UnityEngine;
public class ProjectileMovement : MonoBehaviour
{
private Rigidbody2D rb;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
rb.linearVelocity = Vector2.up * 5f;
}
private void Update()
{
if (Camera.main != null)
{
Vector2 viewportPos = Camera.main.WorldToViewportPoint(transform.position);
if (viewportPos.y > 1.1f) // Bullet is off the top of the screen
{
Destroy(gameObject);
}
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Obstacle"))
{
Destroy(gameObject);
}
}
}
So the bullet is moving straight up

Is it perhaps.. child to the player or some object in the scene etc?
It is a child of the player
Oh
You shouldnāt, as it will move if the player move, the move of the player will be applied on the bullet
I see
As exemple in unity you create a cube
Create another cube as child and move it away
Then rotate the cube parent, you will see the child will move around the parent
Interesting. My current structure is, that the player is the parrent object with guns as a child, the individual gun as another child and then the bullet as the last child
Oh š
The bullet must be free , otherwise, it trajectory will be affected by the player 
@wintry quarry
I don't know where to call my bullet now
The new bullets are spawned at the top of the hierarchy so it doesn't matter where the original is
I'm guessing it's bouncing off the player's collider
If it were bouncing off the collider, wouldn't the first bullet be affected then too?
Depends where the spawn points are. Maybe it's far enough to not hit the collider
Disable the colliders and see what happens

You can disable the collider of the gun
I am sure the bullet spawn point is a the end of the gun lmao
The player collider was the issue
Maybe you should show us the console logs.
The console logs with 1 or 2 enemies?
Two so that we can verify if they're both targeting the correct target
Okay sure
It is, but I guess, because the second shot is ligthly delayed due to the animation, it hits the player
Thats all I have
You're using Find in Start which has potential to behave unwantedly with expectations (especially if the enemy ais are tagged players too!!!)
Animation? All animation or texture should be in child and not having any collider
Hey all, was wondering if there were any good reliable resources to start learning C# , this would be my first time working with any kind of coding or programming. I apologize in advance if this is the wrong channel for this
I can't read that file
Ok ill put them in a paste thing hold on
A tool for sharing your source code with the world!
No no. I mean my gun is a twin gun, but the second barrel shoots like a moment later
why wont the circle appear on the game tab
Oh i see okk
Are they actually shooting at the player though?
Do the bullets fly towards the player?
Yes i see the bullet flying at the player
yes i see them
is that a 3d object?
and the particles too
2d
So their targeting is fine
is it in the canvas in the hierarchy?
Yes it just when there is 2 they both just sink in the ground and dont move
its in the assets but it is spawned in with a button
yeah but do you parent it in the canvas when spawning?
how do i do that
show the code how you spawn it
Try logging stuff relative to their movement ie distance from player
alright sure
it was made with ai btw
please post it like in !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.
how
configure your !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
ā¢
Visual Studio (Installed via Unity Hub)
ā¢
Visual Studio (Installed manually)
ā¢
VS Code
ā¢
JetBrains Rider
⢠:question: Other/None
huh? it doesnt look unconfigured
i dont understand this
You showed the rock code, not how the rock is spawned
the classes and namespaces aren't colored
None of this shows any instantiation logic, you may not be spawning the game object at all unless it's handled in another script?
ah, vs again š
what is that
visual studio / visual studio code
you're using the latter, so click the link that says vscode
Would it be possible to get the y vallue of the parent object and then enable the collider of the bullet, after a certain value is reached?
i clicked it
what is localizedString?
https://paste.mod.gg/olzdwdbkwvms/0 I could only put a bit of it as it was over 36k lines long and idk if it is important but as the player i moved around and moved closer to the ai myself
A tool for sharing your source code with the world!
what do i do after clicking it
What do you mean ?
The distance from the player ? Yeah you can
Personally I'd just disable collisions between the bullet and it's shooter I think that's much easier
But i donāt see the utility
why do you think it would contain "OldValue"?
As if you shoot short range on a wall, it wilā just pass through it
follow the instructions there in the webpage
How, if I may ask?
but i already have visual studio code
Good point
Physics.IgnoreCollision
right, but you haven't configured it
those are instructions to configure it
Hmm, the data all show that they're at their designations minus some offset on the y
I am not 100% sure cause i havent used unity localization, but i would assume if you add a field that already exists, it overrides it
Thus why they may be digging their graves because they're at the location minus y offset
How do I get the collider of the parent?
EnemyAI current position: (-25.00, 1.42, -25.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:50)
EnemyAI destination: (-25.00, 1.17, -25.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)```
what's the content you're getting?
So how do I fix it i assume them both digging to their graves is the reason they do not move
can you show how you initialize the localizedString?
why do i need to do this
Whatever you've set at the target likely isn't correct. Show your modified code with the logs
Or on the onCollisionEnter you can just check the tag of the collided object and if it's the player or enemy then do nothing, depending on who's firing the bullet
If could be you simply logging the incorrect reference
it will point out errors in your code and provide intellisense, and it is a requirement to get help here
is it perhaps just not finished in the same frame?
the target is just player which is me https://paste.mod.gg/mfaokldjfkml/0
A tool for sharing your source code with the world!
ill have to go check the source though...
what does that mean?
are you using the variable "value" anywhere in the base string?
Like i said please show how you initialize that localizedString
quick check you could do to see if that's the case would be to try making a coroutine that waits a frame then logs, or just log it in update or something
also yes try previewing your smart string
i dont understand the page
Log the last target position
sure
should i move or stay still
i deleted console by accident
Doesn't matter. Log it and see if the value changes
ok
alright, what magic/initial string is in your binding for that one?
I'm going to assume the path isn't valid for some reason thus why you're getting your original position etc
If the agent has no path or requested path - returns the agents position on the navmesh.
https://docs.unity3d.com/ScriptReference/AI.NavMeshAgent-destination.html
@fresh fox
well you are not using the value variable anywhere
mhh maybe see if you have access to that in code
Suggesting that this cs Vector3.Distance(lastTargetPos, target.position) > 0.5fmight not ever be true
I replaced my debug logs with Debug.Log($"{gameObject.name} lastTargetPos: {lastTargetPos}");
Then it says EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
And the other one was changning a bit EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
EnemyAI (1) lastTargetPos: (-5.20, 1.33, -13.93)
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:49)
sorry for filling chat mbmb
Yeah, last target position isn't ever updated so we're certain some lines of code are never executed
What would be the quickest fix?
In particular this line where it's supposedly set ```
if (Vector3.Distance(lastTargetPos, target.position) > 0.5f)
{
agent.SetDestination(target.position);
lastTargetPos = target.position;
}
You need to figure out why the distance between the last target position and the current target position is less than half a unit
was it the unity extension that i had to install
https://docs.unity3d.com/Packages/com.unity.localization@1.4/manual/Smart/Choose-Formatter.html
Basically you can look if value exsists and only show it if there is a value in there, otherwise omit it
Could i lower the threshold to something like >0.1f to see if that changes it?
Because it is bizarre how it works when there is 1 by itslef
I don't believe that's the issue
Log both the last target position and current player target position and see why it's less than half a unit
You only need to post a single iteration of messages for both objects (don't spam chat)
I tried to use ignorecollision, but I get a nullReferenceException, when I use it. I am using a while loop to climb the hierarchy and get the parent I need with the "Player" tag, because I need the collider from that parent object.
It is in the script of the prefab for the bullet.
private Collider bulletCollider;
private void Start()
{
bulletCollider = GetComponent<Collider>();
Transform t = transform;
while (t.tag != "Player")
{
t = t.parent;
}
Physics.IgnoreCollision(t.parent.GetComponent<Collider>(), bulletCollider, true);
}
Ok will do
Ok I put this
float distToTarget = Vector3.Distance(lastTargetPos, target.position);
Debug.Log($"{gameObject.name} lastTargetPos: {lastTargetPos}, target.position: {target.position}, distance: {distToTarget:F3}");
if (distToTarget > 0.5f)
{
agent.SetDestination(target.position);
lastTargetPos = target.position;
}
Into my code and this happened the first line when i pressed play looks a bit weird no? https://paste.mod.gg/hcsjmjelgnjp/0
A tool for sharing your source code with the world!
Were you not moving?
Are you at the center of the map/world?
I moved a tiny bit should i be moving more I am spawning at 0,1,0 i think
Your position says you're at the dead center of the world minus some offset
Ill move a lot and send over the console
Either way, the value should be larger than 0.5f but the if statement isn't true
So what is the issue? You are not making sense sorry
EnemyAI lastTargetPos: (0.00, 0.00, 0.00),
target.position: (0.00, 2.33, 0.00),
distance between lastTargetPos and target: 2.330``` The last target position isn't ever updating. It should not be (0,0,0)
It should have been (0,2.33,0) etc
`EnemyAI (1) lastTargetPos: (0.00, 0.00, 0.00), target.position: (0.00, 1.00, 0.00), distance between lastTargetPos and target: 1.000
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00), target.position: (0.00, 2.33, 0.00), distance between lastTargetPos and target: 2.330
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)
EnemyAI (1) lastTargetPos: (0.00, 0.00, 0.00), target.position: (0.00, 2.33, 0.00), distance between lastTargetPos and target: 2.330
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)
EnemyAI lastTargetPos: (0.00, 0.00, 0.00), target.position: (0.00, 2.33, 0.00), distance between lastTargetPos and target: 2.330
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)
EnemyAI (1) lastTargetPos: (0.00, 0.00, 0.00), target.position: (0.00, 2.33, 0.00), distance between lastTargetPos and target: 2.330
UnityEngine.Debug:Log (object)
EnemyAI:Update () (at Assets/EnemyAI.cs:51)
`
So why isnt it working?
It isn't ever changing. Either you're setting it back to a vector zero somewhere or that statement isn't ever true. Put a random log in the if statement and see if it prints
Ok i am putting that in and I am going to move and show u the console once again
A tool for sharing your source code with the world!
I'm guessing it works now because your last target position is updating now
Nope they are both still chilling in the ground haha
Well, the destinations are properly being set. Maybe they're unable to move because there isn't any valid path (bake the nav mesh etc)
Already have as I said it works fine if there is only 1 of them
Unless i need to bake again after duplicating?
Do i bake just the ground?
I assume yes
Also, I'm not sure if the player floating is reachable
Try placing the player at like (2,0,5)
When there is just 1 it just runs towards it and shoots like it is supposed to
Sure
There's probably more change that's happened than you think has happened
Well all I did is duplicate it and change the x and z of the duplicated one
if i delete it
and then just have the original one it works fine
its just the second i duplicate it to have 2 they both break down
I fix it may be an unfixable issue
tbh
I WORKED IT OUT I THINK
I THINK WHEN I HAVE 2
THEY BOTH GO INVISIBLE
and they then follow me invisibly
and there almost shell is just sitting there
and the soul follows me
i have this public static void for my multiplayer game but i seemingly can't run serverRpc stuff inside.
An object reference is required for the non-static field, method, or property 'Sound.PlaySoundServerRpc(AudioClip, Vector3, NetworkObjectReference)'
a static method cannot call a non-static method without a reference to the object you want to call that method on because static means it is not part of a specific instance of the class
so how can i still have a universal function with it not being static?
wdym by a "universal function"
the function of the universe
the irony of codebeginner with Networking questions
The problem is not having a static function it's what you're trying to do inside it
You can't do non static stuff in a static method
It doesn't make sense
You're going to have to show your code if you want more specific actionable advice
i'm just gonna do it like this
public static scipt instance;
void Awake()
{
instance = this;
}
i mean, technically you can if you pass the object you want to interact with as an argument to the method, but then at that point why isn't it just an instance method anyway
also its not about the networking tho! it's about the fact serverRpcs can't be static.
this is a very naive implementation of the singleton pattern. but you still haven't even bothered describing what you are actually trying to achieve by making that method static so whether that is the right move or not is unclear
so that any scipt can access it i.e a sound player script like CustomSoundPlayer.PlaySound(sound);
any object can access any public method provided they have a reference to the object. which is what you are providing using the singleton pattern there.
Showing the code that has the error would really go a long way to helping you understand here
ok. i've realized you can't send audioclips via serverRpcs.
Typically for assets you would just send some kind of ID for the client to look up the asset locally
how could i do that?
would i make a function i could call that would get every audioclip in the project and save it to a list/array?
yo, idk where to say this since its a big server, but does anyone know how you make first person with animations and you can see your character? cause i dont wanna use a normal capsule. i tried seeing some tutorials but they were either; really confusing or outdated, so i was hoping i could get help here.
uhh... the capsule is just for collisons you add a model with animations on top.
basically the character im using is just basil from omori (in 3d) and i ported it over from gmod, got it into blender, then into unity and then into mixamo which finally fixed the bones in it, but im very confused about it
alr alr
but your also going to have to learn how to use unity's animator etc... there should be some tutorials online.
either have a full model that you can see, or have a specific first-person model that only you can see (since sometimes the full third-person model looks weird when looking down at yourself)
not a code question though
do you know any channel i can post this in, it could help
any ideas how i could do the id system?
Have some audio manager that references an audio source/clips and send the necessary data over the server to be able to play that source/clip on other clients etc
alr, ty!
but you should start researching in !learn or via google
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
Data may consist of things like.. an index of some array to indicate which audio to play and location of source, if 3d sound is necessary etc
yeah but how do i get the id and how to get the audioclip from the id.
I believe they were suggesting that you make up some sort of identifier. It could be an enum, a value or whatever
#1390346776804069396 not a code question
Sorry. I don't have that as an option on my discord š
OK...that's it. Thanks for the directions!
hey, i am making a soccer game in unity, can someone help me increase the shooting speed or add a power shot
Whatās the current code? Can you not just multiply/add a number to the code you use to launch the ball?
I have no information, I just want help
ı need powwershot
what part are you stuck on specifically?
making the shot powerful, the input, the graphics, etc?
i don't feel the code is working
Can you check if there is any mistake if I send you the 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.
You can send it here with the links
wha
how exactly isn't it working?
you gotta provide more context/info than that
we aren't psychic
Okay, here's the screen, I'm sorry, letme show you like this
Like what?
game
bro reply pls
you send nothing
bro I don't have any information either
my friend is asking
what should I send ?
the code
we cant help if we dont know what the code looks like
or what the issue is to begin with
@past sentinel
The code looks like smash acceleration
mean powershot
visual studio code
that doesn't give us any info at all
you need to send the actual code as mentioned here #š»ācode-beginner message
and describe what issues you're having, other than "it doesn't work"
they sent it to me one sec
Gotta love a "help plz read my mind thing no worky"
Then have them come here and ask instead of you playing carrier pigeon
could be a language issue
maybe the other person dosent know English all to well
I wasn't at the computer, I came and did you understand the error in the code?
you didn't tell us what the issue was
hey
I paste the code, activate it, but it doesn't work in the game.
this code
I don't know either, that's why I'm trying to learn from you. I don't know if there is a mistake in the code, I paste it into visual studio and save it, and when I enter the game, my shot
no, you do know the issue
You need to start with :
- How do you expect it to work?
- What is happening instead?
if you didn't have an issue you wouldn't be here
something is happening that you don't want to happen, or something that you want to happen isn't happening
cI really don't know the problem
Then nobody can help

Imagine you take your car into the mechanic and you just say "fix it?" and the mechanic says "what's wrong with it?" and you say "iunno"
then the mechanic will jsut shrug and do something else
- powershot
2.dont working
please stop with the unnecessary emojis in the middle of convos you aren't in. it's just unnecessary noise
what is "powershot" and in what way is it not working?
how do you expect it to work and what is happening instead?
I am looking wat is his problem
and you can do that silently without spamming.
I want my shot to accelerate but it doesn't accelerate.
If you literally cannot identify something that isn't doing anything unexpected my only conclusion is that there is no problem at all
Ok
Well what did you try?
Show the code
alright, there we go
have you set the values appropriately in the inspector?
is the rigidbody kinematic or dynamic?
I went into Visual studio and pasted the code, entered the game
have you saved and recompiled
Have you logged the force in the function after you computed it
wait
ok and what happens
you firend add me ?
dont working
show the inspector
come dm
no
YOu can do that here
I'm not your personal helper
make a thread and share your stuff
you already shared code
is everything right?
? inpector?
Show the inspector
Yes.
in unity
The window that says "inspector" in the title
Where you set values in the script
no
The inspector
wrong program entirely
Not the code
what
UNITY
Inspector is on unity
Not on your IDE or visual studio
What is Unity?
will this code work from the unit?

You are using unity and you donāt know what is unity ?
I am Turkish
thats a good philosophical question but not one to ask here
just tell me this
I'm clarifying his question
Am I doing the wrong program?
There is literally nothing more to tell until you can show the inspector
Can you tell me what I should do? For example, download some samples.
You should show us the inspector
Show.
The.
Inspector.
Of.
This.
Object.
the one that looks like this
ı dowland this?
you should already have it
Do you even have Unity installed
Unity inspector
Do you even have Unity
can you send me a download link?
no
Is the program this channel is for actually installed on your machine
If you don't have Unity, why are you here
ıdont have unity?
Then you're in the wrong Discord
well thats an issue
have you seen this icon before
Stop making fun of me, I just don't know anything.
we arnt making fun of you
buddy this is the thing you asked about
Either you are trolling or there is a serious language barrier here. Either way I don't have faith we will make any further progress.
I just want to say, what will Unity be good for me? Isn't it for making games?
If you literally do not have the program that runs the code installed then we can't make your code do what you want
I just want to say, what will Unity be good for me? Isn't it for making games?
This is the Unity support server
<@&502884371011731486> attention needed @gentle gale
If you don't have it why are you asking for support on Unity code
And we have put in a significant amount of effort in trying to extract information in order to do so but you just won't tell anyone anything
The question must be how did he end up there without knowing unity
I'm telling you, I'm pasting the code, no way
How are you running the code
we haven't been asking about the code for 10 minutes
do you have a game project
oh it isn't even in a unity project
I did not ask for another screenshot of your code. How are you attempting to run it
just playing with unity
clearly not, this isn't in a unity project
you need to have Unity to play with Unity
yes
I just saved it like this, I'm getting into the game
So do you have Unity installed or not
no
code isn't magic
insataled
it isn't working because you haven't done anything that would make it work
just existing doesn't make it work
Then how do you intend to run the code
This is not how the code works
Or I'm just injecting it into a game, I'm not making a game
cool, we don't support modding here š
good luck with... whatever you're trying to do
Christ it's a fucking mod I'm not dealing with telephone with two people who don't speak English to support a mod that's like four steps of misinformation I'm on vacation why am I even here
it probably won't help but hey, we tried
is modding a touchy subject here or is it just "we dont help them"?
4 is putting it lightly
omg... ıdont sayI don't want to say anything to you..
you could have just told me the problem
we don't support it here, period
its a server rule
okay then
for legal reasons, and also because it's quite a different situation than the normal unity dev we typically discuss
Its not allowed here specifically because people doing it are unable to do basic things like showing the inspector and it usually only comes about after hours of "I just can't show you that bro" before they reveal why
It's a gigantic waste of everyone's time
anyway so i remember there's a thing for this but i forget how it works. I'm basically wanting an input output system. Input scripts look for Output scripts and run a function called Activate(). I remember there being a way to have a group of scripts share a common thing but i don't remember how it works
"just Debug.Log the value"
"i can't, i need to inject raw ui math as machine code"
Interfaces
quit spamming
that sounds kinda like a bus..?
the way you've described it at least
you could do Scriptable object if they are sharing data ?
but yes interfaces sound like what you're looking for
okay then
to summarize i want all things like doors, and whatever else i may need eventually turn on/off like platforms can use this (idk if class is the right word?) to be told when an input has turned them on or off
interfaces
okay then ill use interfaces thanks
IToggle implemented with method void Toggle
You can commonly call Toggle on any of those that implement IToggle in their class
you are forced to implement the methods and properties of a Interface so you are guaranteed they share it
public interface output
{
public void Activate()
{
}
public void Deactivate()
{
}
}
would it kinda look like this?
c#/cs, not c++/cpp
You just specify the signature of the methods but not actually implement them in the interface
and the methods wouldn't have definitions
(also types are PascalCase, also interfaces are prefixed with I by convention)
Can i Use cpp in unity?
i mean, i guess?
but unity uses primarily c#
you'd have to define extern'ed methods in c# anyways i think
You Thing that c# is better
i don't really know the workflow there
Ok
no language is really "better" than others
they are suited for different purposes
but c# is definitely much more straightforward to use with unity
unity's workflow is kinda built around c#
use c#
if you're still asking, that means you don't have enough experience to decide
just use c#
You can't use anything but C#. Implying there could be alternatives is just misleading.
can you not use extern'd stuff?
Like are we playing the "well technically" game because then yes, technically anything is possible.
ah, i thought it was a practical option
good point
how do i get all the audioclips from a folder/entire project into an array or list?
runtime code or editor code?
editor code.
you can use AssetDatabase.FindAssets() with a folder and specify the type with t:type
https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html
e.g. "t:Texture2D"
or use search service
wouldn't this be for runtime?
oh wait nvm
AssetDataBase is editor only
hmm @patent wedge by editor code i mean in editor outside of play mode
thought this was a function :/
huh?
wait it is no?
in editor we can freely search the asset database using this
for runtime/play mode code we are restricted to FindAll/Resources/Addressables
It is a function
huh? 'Texture2D' is a type, which is not valid in the given context am i forgetting a "using"?
AssetDatabase.FindAssets("t:Texture2D");
the search string supports this type filter
then couldn't you just fill out the array with the audio clips? you cant run functions outside of runtime so how would this work huh?
oh i'm stupid i forgot the "".
you can use it in editor runtime, not built runtime
Ill point out again that this only works within the editor and is unusable in any build
oh i see what they meant now
so this is a string how to i convert it to a list or array?
CONFIRM WHAT I ASKED
i thought they were saying that they just wanted to fill out an array in the inspector
š otherwise we will go nowhere helpful
we can use this as editor only automation to find many asset guids, load the assets and populate some serialized list/array
what do you mean?
what do you want this functionality for
The AssetDatabase class is only usable in the unity editor. It is UNUSABLE in a build. It can be used in editor to automate things or manipulate the project in ways not needed during gameplay and builds.
plz confirm what you require this for
i am not using it in the game i just wanna fill out a list/array with all audioclips from the entire project!
great great then you can use it, you get an array of GUIDS which can be used to load the assets you found
https://docs.unity3d.com/ScriptReference/AssetDatabase.LoadAssetByGUID.html
it says that 'AssetDatabase' does not contain a definition for 'LoadAssetByGUID' do i have to put the script in an editor folder or...
Check the docs in case that was added in a later unity version but otherwise convert from guid to asset path and then load
Hi, everyone.
Are there any prerequisites before learning SOLID principles?
I have used object-oriented programming with other programming languages but not with C# (I'm a beginner with C#).
Any advice?
!csds
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
hey
can ı keep a static bool in a json?
ım newbie sorry for basic question but ı need answer
This question doesn't make any sense
I think what you're actually asking is "can I serialize static variables to JSON" and the answer is you can do whatever you want, but presumably you're using some existing JSON formatter and most won't do that, no
It's not a good idea anyway. It's best to put all your serializable data in a class, without any static anything
save and load is very simple once you understand the basics
- decide what data you want to serialize
- create a class that holds all that data
- create an instance of that class to hold the data at runtime
- save/load it from json as needed
most beginners fail to do step 1 and 2.
also is there anything ı can use instead of statics?
ı use it bcs ı dont use dontdestroyonload
so ı have a character in every scene
You should use DontDestroyOnLoad to have a script that persists between scenes and holds your serializable game data.
Talking about a singleton game data manager, not the character itself.
It depends on what you're using static to specifically solve
like hp,monster statements(alive,dead)
You can do that without static with just normal proper referencing
so ı should use a gamemanager script with dontdestroyonload i think
something like that yes
@wintry quarry sorry for ping but should ı add the gamemanager to all scenes with auto destroy if there is more than 1 will it be a performance lost?
or should ı create a system that if there is no gamemanager in the spesific scene it will auto generated
The game manager would be using the Singleton pattern. Which would limit the number of instances to one.
so if i add the gamemanager to all scenes for save and load later it will be ok?
i tried and it works for me now
but wonder if it will be a problem while save and load
u usually add the gamemanager to the first game-scene (then its DDOL)
meaning the next time u change a scene it comes along..
DDOL objects get put into their own scene which loads alongside the other scene
having the gamemanager in every scene is redundant.. b/c the singleton pattern will realize theres already one and destroy itself
the problem is if player starts in second scene i mean
he played the first scene and saved it
then it will be start from second scene
if there is no gamemanager object in second scene
how can ıt run as dontdestroyonload
well if it was in the first scene or the ones before that it'd already be there
but u can initialize it and start it in the 2nd scene (if thast when the game actually starts) it kinda depends on its job as well
my gamemanager keeps track of the menu settings and stuff as well so mine loads in the first scene
can you call functions in Scriptable objects from other things? probably stupid question
I have a scriptable object that rolls random loot and the get lootdrop function is on the scriptable object so could i call it in my UI? im guessing so but want to double check
Yeah theyād need to be public tho
okay thats fine it is
would i have to call the specific LootTable Get random item thought or just in general im guessing the specific lotttable
You need to get the script on whatever onject itās on
Hey! I'm a very new 3d coder (and coder in general), so if there's anything that seems awfully weird, that's probably my doing š
Please let me know so I can fix it, even if its not apart of this question š§”
Currently, I'm creating a movement system using the Unity 1st Person Starter Kit as a backbone. The main thing that I want to do is create a sliding mechanic: when the player presses the sprint and crouch button at the same time, the player character does a slide. Whenever I attempted to do this though, it would only go to Sprint or Crouch, not the slide speed.
Here is the code: https://paste.ofcode.org/399bzBcp5z7fKuwBe3HF2Rf
Any ideas as to how I can create this new mechanic? Thanks! (Please @ me if you respond!)
Walk through your if else logic. It's broken
Remember code always runs from top to bottom in order.
Gotcha. Thanks!
i have a question, when would you need to make a variable private?
i mean, some variables i dont need to be ferenced, but sometimes they originally weren't and then they were, and then i had to change them manually, wich i wouldnt if they were public in the first place
so why are variables set to private?
So you can't modify them outside the class. It's purely organisational.
All variables should be private unless there's a good reason to do otherwise
as a rule you don't want to expose anything uncessary to outside classes
A good case is say you have a check to see if the player is grounded. Nothing will ever edit it outside of the player movement and only the player movement needs to check if the player is grounded so you donāt need it to be public
And also in modern Unity, all public stuff like an int or whatever is a field
These aren't the best reasons for it to be private actually.
The best reason is that you onl;y have the correct logic for checking that in one place, so there's no good rason an outside piece of code should be able to modify that variable. It invites bugs.
if you need to access it from outside you should create a limited accessor that doesn't allow setting
It's a principle called Encapsulation: https://stackify.com/oop-concept-for-beginners-what-is-encapsulation/
It stops you and others from modifying the variable directly as this creates bugs. If it must be referenced or changed from outside the class, there are other (better) ways to access it . . .
Itās just the first one that comes to mind for me
Editing a thing you didnt wanna edit
i think it makes sense
imagine if you were driving a car and instead of just seeing a steering wheel and a couple of pedals you also saw like the engine's timing belt, the pistons, etc
it wouldn't be great if you started messing with that kind of stuff while just trying to drive the car
encapsulation is the principle that we should only present the steering wheel and pedals to the user, and not all the internal workings of the car
makes sense
Thatās a great analogy
I just started making games and have no idea how to code can anyone help me
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
!learn š
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
š
Hey, how would I get mobile controls to work here? I followed a tutorial to the tee, but it doesn't move my character.
- On-Screen stick set to left stick gamepad
- Player tagged as Player
- Left stick gamepad in input settings
- The snippet of code in the Player that detects input
your code is using the old input system
which completely ignores all of the rest of the setup you showed
you would need your code to use the new input system and use an action bound to Left Stick (Gamepad)
On Screen Stick is part of the new input system - it doesn't work with the old.
Gotcha
#š±ļøāinput-system will be the best place to ask further questions
Hello everyone!
I'm working on a map strategy game and have started making a pixelated region map
Some closer shots
It's set in the medieval period and I want the player to be able to place castles on the map
For that I'd like to make a tilemap out of my image.
How can I make a tilemap where each pixel from this image is a tile?
- Why a tilemap?
- Why a 1 - pixel tilemap?
Nothing about this seems conducive to a tilemap to me
Tilemap is for when you have tiles (repetitive sprites that you use to build up an environment)
that doesn't fit this situation
You may be right, since this kind of game is entirely new to me I am open to other suggestions on how to make it happen
If you've ever played the Civilization series the map is made of of thousands of hexes where you can place cities
Kind of what I want to do here
civ certainly is not a "one tile per pixel" kind of game
A Civ map is like... 1000 tiles
The images you shared above are approximately a million pixels each
I see what you mean. Probably not a feasible thing
What I would really like to know is if it's possible to kind of slice the map up in Unity to make tiles out of it
The way I see it you have essentially two options, and a tilemap is not necessarily involved in either of them
- Take the image as-is, and just overlay a hex grid on top of it. You could use some heuristic like "the color with the most pixels in the cell are what the cell counts as"
- Take the image and run it through a "hexification" pass, which you could write yourself in C# or possibly using a shader, where you walk through a hex grid covering the image and for each cell you look at all the pixels in that cell and analyze them to decide what color that cell should be. The end result is a much lower resolution image in approximately the same shape but made up of "hexels" (hexagon pixels). YOu can then do option 1 and the visuals will line up much better
Unity has a Grid component (which TIlemap uses) that lets you deal with grid coordinates more easily (can be square grids, hex grids, 2d or 3d)
I did not know that. Thank you for telling me
for the hexification thing you could certainly take the image as an input and output a tilemap, if you wish
that might be the most straightforward way
I guess I could also just make it so that when you are trying to place a city/castle your mouse would just snap to intervals which line up with the pixels
The point of having "tiles" for me is that when you place a city there's would be a radius around it, and the amount of water and land in that radius gives different benefits
So in my mind being able to count how many water and land pixels (which I thought tiles might be good for but maybe not now) would yield different benefits
Maybe there's another way to do this that doesn't involve making the tilemap? Because as you said it would be quite large
yeah but that's just part of the grid
Tilemaps are for rendering repetitive sprites in a grid
ultimately a Tilemap is an optimized sprite renderer for displaying a large number of repetitive sprites in a grid.
The grid part is just... a Grid
Ah I see... think I had a misconception about what a tilemap is š
How could I go about making a grid for the map? If you don't mind my asking
It's just a component
you add it to a GameObject
then it's there
you interact with it through scripting
Thanks so much! You saved me a lot of time and headache here
I will do some more research into that
where can i learn 2d random map gen i find some good videos on youtube but not realy what i was searcing for i want to create tons of room as prefab and randomly use them on map
https://paste.mod.gg/ekdgsoqttzei/0
It's not a float, it's a vector3 bruh
A tool for sharing your source code with the world!
Oh my I'm stupid
Hey I got a simple question
If im using a canvas to hold a script that uses an event trigger can I just put a secondary script in that for another clickable ui?
guys any idea how to fix this problem?
Which one?
it kinda go trough the wall
I want to make the cube I'm holding always shows up and don't go trough objects
Either its own pass or a second camera to render after the main content
Sorry I didnāt really get it
the box clips into the large box because depth and that's working as we expect
the easier fix you can try is a second camera that draws only this on top of the main camera.
ask for further help in #1390346776804069396
Oh I kinda get it, thanks for the idea
Can someone help me, why is my albedo all white? I want to make it a cloud shape
Guys any pro c# devs here?
i need new input system pro lol
!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
Kay
Hey I need some help on this movement system in my game. (I'm using using Unity 6)
I want to set a limit on how fast the player can go but it only controls the speed in one direction and its just broken in general
if (Input.GetKey(KeyCode.Space)) {
if (rb.linearVelocity.x >= 5) {
rb.linearVelocity = new Vector3(0, 5, 0);
}
if (rb.angularVelocity.x >= 5) {
rb.angularVelocity = new Vector3(0, 5, 0);
}
if (rb.linearVelocity.z >= 5) {
rb.linearVelocity = new Vector3(0, 0, 5);
}
if (rb.angularVelocity.z >= 5) {
rb.angularVelocity = new Vector3(0, 0, 5);
}
rb.AddForce(forward * 2f, ForceMode.Force);
} else {
rb.linearVelocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
Is it possible to make a shader that will cut this off?
I mean this boards, to connect edges of faces based on heightmap(tessellation)
Still not quite clear what you mean. Do you have an example or can explain better?
I'm trying to make something like this, but when i use POM and tessellation, i get this...
Here it is..
How are you using tesselation?
As for POM, it doesn't alter the mesh geometry, so if you look at parallel to a surface, it will still seem flat.
In the second screenthot it seems like POM is working correctly. I can see unevennes in the surface
So how to get this 3d effect...
Here's Tessellation Displacement
Do you have enough vertices to displace though?
Can you show the mesh in wireframe mode?
The first screenshot here doesn't necessarily have that though. It could just be good quality textures/maps + POM. It's impossible to say from that view if they displace vertices or not.
uhhh, how can I change the default 3d Transform values, do I have to use Blender or something?
either use blender or introduce an empty parent object in Unity and offset/rotate the renderer/collider of the object as a child of it as needed to get the desired position/rotation
If your object has a Rigidbody, that should go on the parent.
Renderer and collider go on the child
It's just cube
I guess Blender is the better choice, but I will see thanks for the idea
When i look from right for example, it's still straight efge
Well, then you don't have much to displaceš
Yes, that's normal. POM can't help with that. You need a lot more vertices(possibly via tesselation), and vertex displacement via height map or something.
And by the way, it's not clear where you plug this into.
U mean change tessellation triangle size?
Here's sphere, but it doesn't seems realistic 3d too
Well, there are many things that make it less realistic. If we're talking about geometry, it doesn't seem like you're displacing the vertices properly.
Right now I'm using this child object's script to detect ground and oneway platforms
public class GroundTrigger : MonoBehaviour
{
public Player player;
private void OnTriggerEnter2D(Collider2D collision)
{
int layer = collision.gameObject.layer;
if (layer == 3)
{
player.OnGround = true;
}
if(collision.tag == "OneWay")
{
player.currentOneWay = collision.gameObject;
}
}
private void OnTriggerExit2D(Collider2D collision)
{
int layer = collision.gameObject.layer;
if (layer == 3)
{
player.OnGround = false;
}
if (collision.tag == "OneWay")
{
player.currentOneWay = null;
}
}
}```
But I see another way using `RaycastBox` which keeps everything in player's script and eliminate the child object. Idk which method should I use for my platformer game
That code is a bit messy, I still not finish it yet
Anyways, I suggest you start a thread in #1390346776804069396 as this is not exactly related to code.
Already, but no one ask anything