#💻┃code-beginner
1 messages · Page 822 of 1
what i mean is that when the player moves the mouse down, i want the sphere to roll forward.
so have the down mouseDelta increase a value
look how you did rotation
var newVel = collision.relativeVelocity.normalized * moveSpeed
rb.linearVelocity = newVel;
//or rb.AddForce(newVel)```
So what should I do or replace
frankly this isnt the place for a step by step, its more of a nudge towards a solution
the solution is simple, you set the bool true when moving or flase if not moving
like the original docs shows you do it just using a blend tree and based on inputs value
the isMoving is valid to add, just redundant
Whst u mean redundant
The line 29 should I do animator.SetBool("isWalking", true/false);
Would that fix it
by itself is not going to do much but setting to 1 value every frame.. is that what you want ?
ideally..it has to be based on something...
is how bools are usually used... based on some condition
Right
so what is the condition that sets it to true or false in animator
On the animator it says the book is isWalking from idle to walking mode is true then walking to idle is false
in the code not the animator
What line on the code
You know Update runs every frame
So if you set isWalking to a specific value, it's going to go to that value every frame
Sorry for being so stupid
Right so should I do a value number
And not true or fake
False
Do you want a number or do you want a boolean
What’s a boolean
look it up
I think you might be trying to run before learning to crawl and thats whats messing you up
Sometimes yt helps but this animation way isn’t helping lol
yt itself doesnt matter its what you looking up that does.
You need to start from the ground up, you're juggling multiple different things at once
Because you're supposed to actually think about the things you're doing and learn how to put them together yourself
not just windmill slam someone else's code into your project without reading it
Yoo
I just started learning Unity and I'm making my first project, I'm really confused on something.
I'm trying to make a simple rectangle with length, width, height, x and y position, etc. and I see on Unity's docs something called Rect https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Rect.html
I have no clue how to use it. I've tried searching online for vids on it, but I can't find anything honestly. Sorry, I'm really new to Unity and I'm a huge noob lol.
I'm also using Unity2d, so I don't know if this is only a Unity3d specific thing too.
Rect is just data about a rectangle so
This just generates the mathematical concept of a rect. If you want one that's visible, you should use a sprite. If you want one dynamically generated at runtime, try a line renderer
Oooh okay, I see.
Perhaps a full game course is what you should start with https://learn.unity.com/course/2d-beginner-game-sprite-flight
In this course, you’ll build a 2D game in Unity — starting from a completely blank project with no assets provided, you’ll create the entire game from start to finish. In the game, you fly a simple triangle-shaped ship using mouse clicks (or screen taps on mobile). Your goal: stay alive for as long as you can by dodging flying obstacles wh...
Interesting, okay. I'm using something called a 2d primitive rectangle primitive https://docs.unity3d.com/6000.3/Documentation/Manual/2DPrimitiveObjects.html#square which kind of gets me what I want, actually.
I guess I'm basically trying to find a way to change the width/height of that white square primitive sprite, essentially. The closet thing I see to that is changing the values of transform scale, but I'm not sure if that's the same thing as width and height.
I'll check that out, deal. I went through this tutorial before https://youtu.be/XtQMytORBmM?si=AIjECmewUdV06j5O and I can also go through that one. Still figuring this stuff out.
Yes, you'd probably be changing the scale. Keep in mind that the scale is in world units, not pixels. Sprites have a "pixels per unit" value you can use if you want to do some math to get specific pixel sizes
^ yes scale is the way
Oooh okay, so scale is essential that.
That makes so much sense. The naming was really through me off, got it.
It's called "Scale" instead of "Width/Height" because you're not always dealing with basic geometric shapes
I see, yeah.
Thank you
I also notice that when I put the scale value of y to 0 (essentially, making the "width" of my rectangular sprite to 0), the rect kind of disappears from the whole scene.
Instead of having the rectangle "squash into itself" like this image here which is really what I'm going for.
I can take a vid of what I mean
Sorry why do you think a web canvas acts the same as unity?
This is expected behaviour
Because they're both using width and height, right?
NO
the js rect is being nice and still drawing a border
0 scale smushes the mesh together meaning nothing is visible
scale and size are not the same thing
Oh, they're not the same thing? That makes so much sense.
eg doubling the size keeps the same border, but doubling the scale makes the border twice as large
Yeah, I'm definitely trying to get the size or whatever parameter there is in Unity to get the outcome above.
rect transform... Going to Google that
this is unity ui stuff
no no dont use that
i don't know what the overall goal here is though so my suggestion is without context
Sprite pixels per unit, transform scale and camera orthographic size all matter here
@static laurel what's the overall goal here? kinda feeling like an x/y problem
The unity default cube sprite should be 1 unit wide by 1 unit tall. Here we can take the camera ortho size into account to make it be a certain size on screen (if thats the goal)
You're good. It's very hard to describe what I'm trying to do lol, but I'm trying to find a way to create a rectangle with a height of 0 so I can kind of have it like the picture above where it's collapsed in on itself.
Sounds to me like you want a border around a sprite
Kind of...
Here
So I'm basically making my own "bar fill animation" by having one rectangle and then having another rectangle overlayed on top of it with a height of 0, so that the first rectangle kind of starts at the "bottom" of the second rect.
Then I want the hright of the first rect to gradually increase until reaches the full position of the rectangle that its overlaid over. It sounds so weird but this is a vid of what I'm going for
is this a gameplay thing or a ui thing
Perhaps world space UGUI (ui) would be best
what's it supposed to be
That's why I'm trying to find the "height" attribute of these rectangles in Unity and I was very suprised when I couldn't find anything online for it.
The answer is "its a sprite"
its not a rectangle
(what is this bar supposed to represent)
(just tossing another random solution in the ring but if your just wanting to draw a texture raw from code, this takes a rect https://docs.unity3d.com/6000.3/Documentation/ScriptReference/GUI.DrawTexture.html)
I'm trying to make a bottle that "fills up" with water once droplets makes contact with the rim. You can kind of see the bottle sprite over to the right there and essentially I want to simulate that before in the vid, but in a whole grid system, then I'm going to make that grid extremely small, place the grid inside of the bottle, and then kind of simulate a water bottle/flask filling up with liquid.
Oh god its ongui plz no
ok, this is the X
That one tile is an example of one rect out of a whole grid that I'm trying to get working first. Like get the idea down
You can do this by scaling a sprite just fine, it just needs maths
for future reference, when i brought up x/y problem and asked "what's the overall goal here", the correct answer is just this part
I'm trying to make a bottle that "fills up" with water once droplets makes contact with the rim.
It will be harder because the default square has its pivot in the center
Not that good at math, but I can see if I can figure it out
i don't think scaling would be appropriate here tbh, it'd mess up the actual sprite once you have one
Yeah
you could probably scale a spritemask
that seems.. subpar though
oh right, this exists
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/SpriteDrawMode.Tiled.html
just use that
i forgot SpriteRenderer had these
those 2 modes work similarly, just depends on if the graphic should tile or expand
Sweet, I'm going to research what they do lol
i guess with intermediate water graphics in the middle you'd need it to tile
hi guys
Oh yeah, but this is very beginner lol.
Do these also work in Unity2d?
any of y’all ever played gorilla tag games ? or anything like it? i’m a kinda young coder and i need help with my gane
it’s in prealpha
this.. isn't really a thing
!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
You can literally just use a filled image
apparently this is supposed to be a gameplay element
I considered that, but I could not find any sprites that looked good online lol.
sorry i just needed help
those 2 things are not related
So like, that's a yes? My bad, I'm confused.
Then you should ask a question
unity2d is not a thing
Ohh, I see.
aside from physics stuff
unity3d is one way to refer to the engine because the game engine is 3d
anything 2d in unity is just ignoring Z
there's no unity2d
Yeah, because I eventually plan to have cool things like having each water tile in the grid be able to fall out of the bottle when its tilted, have each tile collide with the ground and make a "splash puddle," etc.
(but yes there are separate physics (3d) and physics2d sets of components because they link with different physics engines)
Actually, is it actually possible to make an animation for this? Like your own sprites, water sprites and stuff?
yes
Oooh
the answer to "is it possible" without constraints is 99% of the time yes, since you just described it
whats goin on
the second screenshot is unrelated
for the rest, socket hang up usually means a network issue
perhaps try a different network
hey guys so how do i make the textmeshpro input field's cursor thing move and have the text stay in place rather than the other way around? the cursor is stuck in the middle of the bar right now
perhaps check the text alignment setting?
like on the text ui object or the input field?
im changing its position upwards each time i click W and it just phases through the solid colllider
Quick question, if i have 5 guns in a game (for a rougelite), should i implement them with scriptable objects or normal mono behavior code for each gun ?
for example imagine the weapons in Megabonk, how would you implement them ?
depends tbh, most likely both but it depends on how comfortable you are with c#
already made the scriptable object one and it's really good with bullet guns(fire rate, damage etc..)
but then you have a shotgun or a grenade launcher...
the general idea is scriptableobjects are for knowing things and monobehaviours are for doing things (this is more of a guideline more than a strict rule)
this means you might have a scriptableobject asset and monobehaviour instance/component for each gun that are kinda siblings (one has the data, one uses the data)
because your guns do different things you would use inheritence to extend on these when neccasary
if you don't know what inheritance is and/or are not comfortable/familiar with it yet then that's probably the big knowledge gap your running into right now
so it's better to do mono behavior for now ? is it a bad thing to do performance wise ?
performance is a complete non concern for anything related to this, don't worry
to keep it simple that's totally ok yeah
ok that's great to hear, so in your opinion should i use mono behavior and do a code for each weapon ? since there's not that many
yes but via inheritance
it's something online stuff will teach you better than i would but it's a way of building off of other scripts
so you would have like
public class Gun : MonoBehaviour
public virtual void Shoot()
{
}
public class Shotgun : Gun
public override void Shoot()
{
}
public class GrenadeLauncher : Gun
public override void Shoot()
{
}
etc.
Very clear, thank you so much 🙏🏻
hi guys, im new here, i just need help on how do i refrence a script or class in another class? all the resources i found were on different problems and didnt help.. SOMEONE SAVE ME AHHHH
Choose the best way to reference other variables.
turns out i made the most hidden typo in history i quadruple checked and jsnow discovered so thanks anyways discord people
!ide 👇 make sure your IDE is configured so you don't make silly spelling mistakes
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
!methods
There's no command called
methods.
!functions
There's no command called
functions.
Ig not
what don't you understand about them
hi, I'm working on a small game where the player is on mars, and when he/she leaves their base, their oxygen goes down, and when they go into the base, the oxygen stops going down. I'm using StartCoroutine() to make the oxygen go down every few seconds. ```using UnityEngine;
using UnityEngine.UI;
using System.Collections.Generic;
using TMPro;
using System.Threading;
using System.Collections;
public class PlayerOxygen : MonoBehaviour
{
public int maxOxygen = 100;
public int currentOxygen;
public oxygenBar oxygenBar;
public TextMeshProUGUI oxygenText;
public bool canBreathe;
void Start()
{
currentOxygen = maxOxygen;
oxygenBar.SetMaxOygen(maxOxygen);
}
IEnumerator LowerOxygenRoutine()
{
while (true)
{
LowerOxygen();
yield return new WaitForSeconds(5.0f);
}
}
void Update()
{
oxygenBar.setOxygen(currentOxygen);
oxygenText.text = currentOxygen + "%";
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag("IsBreathable"))
{
StartCoroutine(LowerOxygenRoutine());
}
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("IsBreathable"))
{
StopCoroutine(LowerOxygenRoutine());
}
}
// Update is called once per frame
void LowerOxygen()
{
currentOxygen -= 10;
}
}
Is it worth reading "write great code"? How I understand it explains, how to write code with machine in mind.
Tryna see the syntax and list of methods
use docs for that, not the bot
bot messages are related to interacting/asking/helping here
surely a coroutine is a massive overcomplication, this could be a accomplished in update easily
A coroutine is fine for that
borderline preferable as with a little adjustment you could remove update entirely from that script
you could do something like:
if (drainOxygen)
currentOxygen -= drainrate * Time.deltaTime
currentOxygen = Mathf.Clamp(currentOxygen, 0, maxOxygen)
not at my pc but along those lines
so its important that the oxygen is lowered by a certain amount in this case? like 10 every 5 seconds something?
i mean i don't know, which is kinda the point
if they want to do what they are doing then coroutines are a pretty fine way of doing so
again can be accomplished in update using a float for timer, personally i would avoid using coroutines for this because as i think i can see, theres nothing that stops this coroutine being triggered multiple times and running simultaneously
for example if you walk between breathable zones,
you could have a flag to stop it but then, solved if it can only happen once in the update loop
which is a fair point, but not neccasarily a reason to not use coroutines, thats just two more lines of code to fix
Better to just fix the Coroutine than to suggest a refactor because it would be better
Especially for a beginner
Because sure, it would be better. But their case is also very much valid and only missing a step to work
Can I write that in C# ?
RunnerEventSystem.OnFlyUp += () => _isFlying = true;
And if yes, how do I unsubscibe the event afterward ?
If you want to unsubscribe, don't use a lambda () => .... Wrap the _isFlying = true; in a method instead and subscribe/unsubscribe that
Your IDE probably has a quick action to convert the lambda into a method
So then you'd have
// Sub:
RunnerEventSystem.OnFlyUp += StartFlying;
// Unsub:
RunnerEventSystem.OnFlyUp -= StartFlying;```
oh I fixed it I forgot to say
it was easy, I just had to add a few things.
Hey
Hello?
hi?
Come dms
I don't really accept DM's dude, sorry 🙁
Come bro i have one question?
Stop harassing people
If you need unity help, ask here (or in another appropriate channel)
++
wanted me to help him make a game?
I have a weird bug in the animator... I start on a walk animation then after some time trigger a run animation, but it then revert instantly to walk right after run has played once
you might want to include a screenshot of your animator with states/transitions.. if you have a transition back to the walk with exit time unticked, then.. that's expected
I do have a transition back with exit time unticked, but it should only happen on a trigger "walking"
no, it will always do that
Then how do i handle that issue ?
actually i'm wrong -and you're correct if the exit time is unchecked and you have no additional conditions, it will be ignored...
so, it's more than likely, your trigger is being triggered multiple times/frames ?
It is not, it's called only in one place and I've checked that it's not called wrongly. Plus I just tested with booleans instead, and in that case it works normally
put a debug.log just before you trigger walking, and check to see if the code / trigger gets triggered
where are you calling the trigger from? a monobehavior or something like a StateMachineBehavior ?
Is it the same trigger, or a different trigger (like different name)
Again i would debug it to make sure it is not being called multiple times...
I have put a debug log before the trigger, it is not caaled wrongly
..the reason i ask what's calling it, is.. things like 'behaviors' or statemachinebehaviors are called multiple times per frame... unlike monobehaviors
I have an event called "On StartWalk" or something like that, that calls the trigger
Hey all, it's probably an implementation issue on my end but I've been trying to get the player's current speed by the rigidbody velocity magnitude, but for some reason even though the speed will reach a maximum and stay constant, the velocity keeps going up as long as movement persists. Any ideas for why that might be?** **
yea idk sorry, could be multiple things subscribed to the event calling it.. in my experience c# events seem kinda 'slow' too, so they have caused timing issues for me.. its quite hard to help with just your text description, sorry
Probably best to show the code
If you are using AddForce and there's no friction or drag/damping to slow you down then you will accelerate forever
now that you mention it, there isn't any linear damping for it
that probably has to do with it
..does anyone know how to get the URP render feature 'render objects' to work with transparent objects, to stencil them out?
-i've got it working fine with opaque objects but i'd like it to work with both transparent and opaque objects...
--Ok nevermind got it to work
it was exactly that, I just had to set the linear damping to 1. Now if I want more precision I can just isolate the X and Z positions as well from it. Thanks for the help
So I just found out a few hours ago I can’t serialize interfaces for dependency injection to the unity inspector, and I saw someone suggest online the use of abstract classes in its place.
public interface ICashDisplay
{
public void UpdateText(int cash);
}
public class CurrencyDisplay : Monobehaviour, ICashDisplay
{
[SerializeField] private TextMeshProUGUI text;
public void UpdateText(int cash) => text.text = “Cash $” + cash;
}
public class SomeOtherClass : Monobehaviour
{
[SerializeField] ICashDisplay cashDisplay; //this doesn’t show in inspector
}
//pretend the naming convention for interfaces applies idk what else to call it rn
public abstract class ICashDisplay : Monobehaviour
{
public abstract void UpdateText(int cash);
}
public class CurrencyDisplay : ICashDisplay
{
[SerializeField] private TextMeshProUGUI text;
public void UpdateText(int cash) => text.text = “Cash $” + cash;
}
public class SomeOtherClass : Monobehaviour
{
[SerializeField] ICashDisplay cashDisplay; //Would this serialize to inspector? Is it bad practice?
}
I’m not at my pc rn and can’t really test it myself, and I also want to know if it’s bad practice to do this (because of composition over inheritence, overengineering, I might need to inherit something else, all that)
trying to avoid tight coupling between some other class and a few other classes cause my code is spaghetti rn. Tryna fix it :(
In this particular case, I don't see any point in having that interface/abstract class in the first place. What other cash displays do you expect to have?
hypothetical example, this isn’t the actual one I’m going to use
But yes, an abstract class should serialize.
Is cheesing it like this bad in any way though?
Not really. It depends on the specific case. As with the example you provided, there might be a better way.
It might be more difficult to replace with dummies for unit testing and such, if you plan to do that. Though, probably still easier than no base class at all. It's not entirely clear what your intention is behind using interfaces/abstract classes.
Mate i’m barely sure myself. I’m kinda coding on what feels right, and if my code looks like soup I’m gonna start digging for a better way to do it. I could be headed in the complete opposite direction of where i’m supposed to be going right now, but i’ll figure it out eventually. First game’s supposed to be the practice run right?
Well, in that case it might be way more useful to share an actual example of your code that you think needs refactoring.
Then we might be able to suggest an actually working solution.
Hey, guys! Is tehre a way to get reference to these color properties??
I thought maybe its color block struct
Which color properties?
oh Color32 struct
Color and Color32 are essentially interchangeable.
Color32 just doesn't support HDR
I wanted RGBA and hexadecimal basically
oh hexa is not there
how to get reference to hexa
rgba is directly available on both and to get a hex string you use this: https://docs.unity3d.com/6000.3/Documentation/ScriptReference/ColorUtility.ToHtmlStringRGBA.html
So, its a static class and I was trying to find the property hexadecimal after declaring the field of Color Utility
So, I see there are some methods including this one ToHTML
from the class itself thanks!
ok, I think I am not sure how to use its methods XD
#base-unity
To use a static method you just do this (ClassName.MethodName(...)):
string hexString = ColorUtility.ToHtmlStringRGBA(myColor);```
the function creates a string, so yeah you would store it in a string variable
The method to parse from a hex colour is a tad different if that is confusing you
or do whatever else you want to do with the string
lets say I want to get this specific value
Yes you use this #💻┃code-beginner message
oh, let me try
if you plug that color into that function you will get the string "959595"
well actually this one includes alpha
so you'll get the alpha too
if you don't want alpha you should use the RGB version
There is TryParseHTML method
I think that one I need
Also, like I see there is a problem using ColorUtility itself because there is a class called ColorUtility on Unity.VisualScripting namespace, so I have tried using the UnityEngine one, I mean why they gave them the same name XD
Thats to go from html string -> color object
You need to explain what you actually want to do better 😐
No, I found a way
No you have it backwards
UnityEngine.ColorUtility.TryParseHtmlString("959595", out Color color);
Thats how I did it
Ok yeah if you're trying to go from the string to the color, you need the parse method
but you were saying you wanted to go from the color to the string
so which one is it?
yea so you explained it soo bad you were told the opposite
p.s. if you're just trying to hardcode a color with hex code 959595, you can do new Color32(0x95, 0x95, 0x95), you shouldn't parse a string here if it's hardcoded.
er actually
bascially the hexacdecimal only
I think you have been told how to go both directions now so do as you need
oh?
Interesting
Just remember that TryParseHtmlString MUST have a # in the hex colour string
e.g. "#FFFFFF"
really though... why not just define the color in the inspector? 🤔
static was mentioned so who knows
public Color hoverColor; // assign in the inspector
public void OnPointerEnter(PointerEventData evt) {
// something using hoverColor
}```
Oh, that's less headaches
I think
Hey I’m metrix and I’m wondering if anyone can teach me how to code c++ our c# pls dm me if you can
check the pins for c# learning resources. go elsewhere for c++
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
You're not going to find a personal tutor here
Thank you
Okey
to clarify, i can have a script reference a scriptable object without that scriptable object being attached to some item, right?
like i can just have the data in a folder, and then directly have other scripts take the data from that scriptable object?
i want to make absolutely sure i'm understanding this right
ScriptableObjects cannot be "attached" to things
you can reference them from anywhere if they're assets, yes
that's the point basically
feels a bit weird but thank you
i know i cant put it on game objects like monobehaviors but admittedly i havent used them a lot for more than like inventories
Why doesnt this work
its not colliding with the oter thing even though both have box colliders
Have you tried this? This should do it.
my brain is struggling to comprehend scriptable objects i think
😭 sorry
Easiest way to think about them is a tiny database in a file. A collection of variables you can assign in the inspector, bundled up and packaged in a tidy little file in your project directory
public class p1 : MonoBehaviour
{
public Rigidbody2D rb;
public float movespeed = 2f;
private bool bordersHit = false;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.W) == true && bordersHit == false)
{
transform.Translate(Vector2.up * movespeed * Time.deltaTime);
}
if (Input.GetKey(KeyCode.S) == true && bordersHit == false)
{
transform.Translate(Vector2.down * movespeed * Time.deltaTime);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
bordersHit = true;
Debug.Log("Collided");
}
private void OnCollisionExit2D(Collision2D collision)
{
bordersHit = false;
}
}
this is 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.
!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.
DOUBLE KILL
if does the one file share information?
fuck
do either have a rigidbody
i dont even know if what i asked just made sense, it doesnt even make sense to me
If multiple things reference the one ScriptableObject file, they have the same data
Yes the uh border has a rigidbody
You should probably never change data on a ScriptableObject for this reason - it can affect other objects using it
and if i alter a value of that scriptable object through one of those references, they all get the update, right?
is it a 2d dynamic rb
this is primarily just for like a save state type thing
show the set up
afaik you generally wouldn't be using SOs for savestate, just a normal class/struct would be perfectly fine for that
Yes, but there's a problem with doing that. Changes made to SOs in the editor are permanent, they'll carry over when you stop the game playing. But in a build, they'll always revert to what they were built as when the program closes.
You shouldn't change data in an SO
When i make it dynamic its getting affected by my push and being thrown
well yes, dynamic rigidbodies are simulated
Im like COMPLETELY NEW btw so sorry if i say dumb things
save/load are insanity im about to just have them restart the entire game and accept it
non-simulated rigidbodies don't experience collisions
ScriptableObjects probably aren't going to be any part of a save/load system
Do you know how i can not make it get pushed @naive pawn ?
there's a lot of ways depending on what you want to behavior to be
eg, if they should not collide, set up the layers to specify that
i just want a border thar can stop my movable object that cnt get pushed around
you're still leaving out a lot of context
it sounds like it's the moveable object that needs the rigidbody
I have it only move on the y axis (its 2d btw if i forgot to mention) and whem it hits the border it also gets pushed and turned 🥲 @naive pawn
Whats a constrant
ok so basically i have a slider thing that i can move up and down but i want to set borders and when it collides with that border i want it to not be able to move that direction anymore so badically not be able to move past it
and what's the current setup
consider taking screenshots of the inspectors for each object
locking position/rotation
How do i do that?
Thank you constraints fixed it
Hello there!
Can somebody explain me what is the meaning of using IDisposable interface in !Unity! scripts? I just cannot find any good explain. Just ehh... event just invokes when game ends, right?
I would be very grateful
It ensures the object has a Dispose() method that can be called when the object needs to be cleaned up. What that Dispose method does is up to the object, it might free up memory or release file handles or do whatever it needs to do when it's done being used.
Presumably, when the game ends, it calls Dispose on anything that implements that interface at some point
Hmm
And in what cases is it useful to use it?
I mean I can write same interface myself at any time.
In all the same use cases that IDisposable is normally useful
i.e. when the object represents some external resource, not just an in-memory C# object
a file handle, a network connection, etc.
Oh, ok
Thanks❤️
Just to expand on that a little bit - most C# managed objects get cleaned up automatically by C#'s garbage collector. But if we're talking about an unmanaged resource, i.e. anything not managed by the C# runtime, those things often need some special handling to clean them up. That's the point of IDisposable - it creates a common, known interface for cleaning up such external rsources. For example releasing a file handle, flushing any buffered bytes, closing network connections, freeing up unmanaged memory in C++ objects with explicit free() calls, etc.
The using syntax is quite handy with IDisposables. For example, I have a type GUIColorScope that temporarily changes GUI.color:
using(new GUIColorScope(Color.red))
{
// Everything drawn here is red
GUI.Label("Yo");
} // Dispose gets called here because the scope ends
// Everything drawn here uses the original color
GUIColorScope sets the GUI.color when it is constructed, and then reverts it back to the original value when Dispose is called
Idk if that's too complex - just wanted to show a practical example 😁
Also if an exception happens inside the scope, it will still call Dispose which is handy so you can always clean up resources.
No, I understand :)
I knew that, but I asked for examples that you use yourself.
Thanks :)
I love this one for poolable collections
using var poolable = ListPool<Vector3>.Get(out List<Vector3> positions);
automatically returns the collection to the pool at the end of the scope
Hi all, I'm developing a multiplayer game that allows for a variety of game modes, and I'm unsure how to tackle this.
I want each game mode to have their own code for various events, as well as certain variables set, all handled through a game manager MonoBehaviour class, so I figured I would create an abstract Gamemode superclass, with the other gamemodes as subclasses of that.
Now I am wondering how to store these classes. Would it make sense to make something like a polymorphic array, using a Gamemode[] array, storing singletons of each gamemode, such that the game manager class can refer to a particular gamemode's code through an index, or is there a design pattern that makes more sense for my use case?
ScriptableObjects with Strategy Pattern seems like a good fit for this. Hard to say for certain without more context but that’s what comes to mind. When a GameMode is selected in game, set the SO on the GameManager and it can abstractly get what it needs from the SO without caring which one it is or the specifics of implementations on the SO instances.
Ohh that sounds good - I haven't actually used ScriptableObjects at all, but I might need to look into that.
For context, my GameManager class just keeps track of various game data, such as which round it is, what teams are which etc. The gamemodes could be Deathmatch and Capture The Flag, where events such as "OnDeath" events would be handled differently depending on which gamemode is active
And so my initial idea was to have the aforementioned array, such that
Gamemode[] gamemodes = { new DeathmatchGamemode, new CaptureTheFlagGamemode }
int currentGamemode = 0;
And the game manager could call for example, gamemodes[currentGamemode].OnDeath();
how can i learn to code becas ik i shudunt use ai olways
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
and the pinned messages in this channel
tho idk how is ses 750 h i see 4 h at max on the site
Hello
look harder then i guess
🙂
i fr dont see it
I need your help. I need to know how to graffiti a wall. How to make it come out of the spray can. Could someone explain it to me? Or where can I find a video that explains it?
Assuming you're using URP, you can use decals:
https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@12.0/manual/renderer-feature-decal.html
Which codes can I use? I've looked for tutorials but I'm still confused.
There is no bult in "codes"
There are many parts to making this feature, I'm not sure how you could expect anyone to give you a definitive step by step guide.
https://learn.unity.com/pathways
how about this?
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
I would start by looking up how to paint things onto a surface, if your graffiti needs to be player made (like look up a tutorial on how Splatoon does their stuff for example)
I simply need a video that's close to what I'm looking for.
Okay, and you want us to find it for you?
What makes you certain a video exists that does exactly what "ELMonoSabio" needs?
god dam and i think the one i shud look up to Junior Programmer when i get it there?
Not much, I'm just compiling every video about how to paint in Unity. From there, I'm experimenting with each piece of code.
if you don't know c# you should start with the beginner c# tutorials in the pinned message in this channel
and then start doing the junior programmer stuff
hey guys, i keep getting the same null exception error even though everything is working fine, can someone help me get rid of this error?
can you show us the error.
Hey, guys! I would really like to learn how to use Scriptable Objects. Can somebody recommend a video or a good tutorial on scriptable objects or even explain to me how I can work with it?
scriptable objects are really just a way for you to define your own type of asset, there's nothing super special about them that warrants an entire tutorial
How I am supposed to start learning how to use it?
look at the docs to learn how to define a scriptable object and create an instance of it
I am just programming using Monobehaviours
I dont know about scriptable and I really want
So, its a data container basically right
it's a way to define your own asset
Can you use methods and more in scriptable object
If I am not wrong there is no Update, Start and some other built in methods compare to mono
you do realize it's just a class, right? there's nothing special about it that prevents you from using anything a normal class can do
if you'd read the docs you'd see you are partially wrong
Hello, I am working on a dungeon generator that uses a dictionary to handle the grid, and when using .ContainsKey, it is still giving me an error? I would appreciate some help with this one.
(The Vector2 key is the grid space, and the Vector4 is for door positions)
@sage mirage the thing about ScriptableObjects is as Boxfriend mentioned they’re just assets defined by you. This makes them very flexible to all sorts of implementations. But if you’re totally new to them then using them as shared data containers is a good place to start.
For example you could have an SO which defines the base attributes of some enemy. Then for example rather than having every enemy instance store a member for, say, movementSpeed, they instead read that value from the asset. This is really handy for testing things out at runtime, because then you can do things like changing that movementSpeed value and all current instances will be using that value and move faster or slower
Floats are not reliable so these keys are probably unreliable. Also you should prefer TryGetValue() instead of what you are doing.
Use Vector2Int if your positions are integers
Oh i just realised the keys used in both operations may not even match (you dont use the same variables?). Anyway i expect my main points to be ignored so
I am currently testing it with Vector2Int, but if you dont mind explaining, why would TryGetValue() be better?
@sage mirage Brackeys’ Hearthstone example is a pretty good introduction to using SOs as data containers.
When making a game you need a good way of storing data. This is where Scriptable Objects come in! In this video we’ll learn how to use them by looking at an example: Making cards for Hearthstone.
● Project on GitHub: https://github.com/Brackeys/Scriptable-Objects
❤️ Donate: https://www.paypal.com/donate/?hosted_button_id=VCMM2PLRRX8GU
...
It lets us try to get a value and then use it in a safer way. Doing Contains() and then accessing it means the dictionary does a look up twice. TryGetValue() is once and just better.
got it, thx
so testing it, it still does not work with Vector2Int, and I have a different section that does a similar thing and works, so I need to look through and see what is different
In your example you do one thing to get the key for Contains() and then seemingly something else so use TryGetValue() to prevent that silly mistake firstly
But yes if your positions are ints then use Vector2Int for the keys to avoid floating point math imprecision fucking up stuff
🤦♂️ What am I doing, that line that checks if it contains the key is calling to get the value of that key lol. I see what you mean. I am clearly not as awake as I thought
Also sometimes its better to make a variable and use that instead of copy pasting some crap like that
That also prevents silly mistakes
also that if else on one single like is discusting ew 😆
that is what I am using UpDoor for
No you made a vector2 for the Contains() check then seemingly try to do the same or something for the [] access
anyway i could say even more but best i stop there
TryGetValue + Vector2Int
One question: what videos do you recommend, or is there a course I need to take to get my spray paint to work on a wall?
Decals
how can i sort these? like putting them under categories or something
in code or just inspector?
just inspector probably
oh thanks
Yeah you can use things like header or custom inspector / editor window eg https://docs.unity3d.com/ScriptReference/EditorGUI.Foldout.html
is it possible to indent the contents? or is it just visual and theyre not really stored under anything
it is but that gets into custom code and/or third party asset territory
or base classes or structs
oh i'll just stick with this then. not really anything other than qol for myself anyways
thanks
How do i make UpdateCardVisuals() any time changes are made to the scriptable object whichGR_Card card is referenced to?
(only in editor)
Without making your own custom editor? You can get the Odin Inspector asset or use free alternatives like: https://github.com/dbrizov/NaughtyAttributes
Specifically, the OnValueChanged attribute
Actually, if you want it to be on values on the SO and not changing the reference itself then that probably won't work
damn
this is in a monobehaviour, it could just make sense to do this in awake/start and have it read the data everytime rather than using this as an editor tool
Otherwise there isnt a great way in general to do this because this monobehaviour would exist in scenes that may not be open, or prefabs too.
Or just use OnValidate
On Validate doesnt work
seems like OnValidate is individual
I see no reason to not just put this logic in awake/start
Even if on validate works, its not going to affect any of these instances if its in a scene that isnt open
Oh nvm you want it to change when the SO changes
dont those not work in the editor?
Why do you need it in editor? This is a monobehaviour, its going to run in your scene
It can run when your object is loaded and immediately set the values of the text elements
its so i can see my updates live
Then id just make it an event on the scriptable object that this monobehaviour listens to, and calls this function you want
It wont necessarily affect a build unless youre trying to update SO values at runtime, which you ideally shouldn't be
yeah dw its just for a in-editor tool
true ill go try that
hell yeah, works perfectly
events seem cool idk why i dont use them more
hello there, anyone want to go over the basics of C# with me?
i can try
oooh yay :) uh how we want to do this?
you can dm me
alrighty
im not allowed to message you 😭
Yes! The more people throwing stuff in my brain the better
Hi all, I'm getting into using ScriptableObjects for my project, and for this example, I'm using weapons.
So I have a ScriptableObject named Weapon, and from that I have Gun, Knife and Grenade.
I have then made a second ScriptableObject named WeaponRegistry, which holds a Weapon[] array, where the different Weapon objects are stored. In a game object in my scene, I have a WeaponRegistry field, where that scriptable object is put, so I can always gain access to the array of weapons.
Is there a better way to do this, or is this fine?
if you are notplanning to modify the WeaponRegistry at runtime, it is fine
are you defining the Weapon type with an enum?
Okay perfect!
Yess that was actually going to be my follow up question - what would be the best way to reference the various weapons? Can I use a WeaponType enum (for example) as a key to get a Weapon object?
sure
What would that look like, the enum's index corresponding to the index of the weapon in the array?
Such that WeaponType.Gun = 0 and weaponArray[0] is the Gun object?
please do not solicit dms
Can you elaborate? I like to think I have a general understanding of how enums work, but not sure how to apply them for my use case
- or how to use the enums to reference elements in an array
@brave helm @white orbit consider utilizing community servers - the purpose of these servers is so there's a large audience to view and answer questions, provide alternate answers, or validate/dispute answers if necessary.
so, just ask here or in the c# server, depending on what you're discussing exactly
and https://dontasktoask.com
delegating to DMs wholly negates the benefits of a community server - being public is the point 😉
if you only have one of each i guess you could use a dict? i'm not sure what murado had in mind exactly though
why do you wan to reference an element in the array, you just want to define the type of your weapon
I need to gain access to the object at runtime, for example for weapon spawning during a game
So I need a way to do something like spawn(WeaponType.Gun)
Would doing that be a fine way, or is there a better-practice way?
Please how do I develop on unity through mobile
you couldn't make this generic in a proper way with an enum 
unity is a desktop app
Ooh
please do not ping specific people for help
why are we mini modding 💀
the type of your weapon is something else and the weaponregister is somehting else.
i'm not trying to moderate. i'm trying to prevent 3 relative beginners from learning poorly
the weaponregister holds a collection of weapons
i js got unity and it wont install?
Sorry, I meant something like weaponRegistry.GetWeapon(WeaponType.Gun)
Not calling the enum directly
just happend to me today aswell, i just did the retry button and it worked just fine 🤷♂️
this is a network issue, try a different network
though i'm not sure the issue is on your end. there's been a few questions about this error and the unity website being broken recently
ok
yeah if it's on unity's end you could only really just try again
So my point is just if there is a better way to access a specific type of weapon through my WeaponRegistry object, other than knowing / remembering that 0 = gun, 1 = grenade and so forth - or rather, what the best way to do this is
@white orbit i explained why DMs are bad here btw, if you need clarification i'm happy to explain further
i clearly dropped it why are you still going-
he helped both of us together in a gc so thats all that matters, but ty though
this is just pre-emptive, i'm not trying to argue here
yeah so like.. you're getting help from essentially another beginner lol
ime, 0% of the people well-experienced in the topic and in teaching said topic are interested in going to DMs.
asking directly in a community would generally give better answers, is all i'm saying
i mean he explained well, and from the manual its the exact same info just worded differently any help is better than no help. so just drop it thanks
he just explained the basics and thats clearly all we asked about
but thanks again
it doesent work still
@solar kettle are you using polymorphism for your SOs, ie can you just use the Weapon type directly rather than needing specifically Gun/Knife/Grenade?
I only have 1 Weapon class / ScriptableObject, and the other weapons are assets off of that
that's not exactly what i asked
to use a Gun, do you need a field of type Gun, or is Weapon adequate where you could use Weapon.use or whatever
Yes that is what I meant sorry :) There is no Gun class to use, just the Weapon class, so a Weapon field is adequate
But I also only started digging into scriptable objects yesterday, so I'm not sure if that is the best way to do it
The Gun exists only as a Weapon asset, with particular name, texture, damage etc.
ah i see, i misunderstood, i thought you had stuff inheriting Weapon
I had that until yesterday :P
that simplifies it then
i think what murado was suggesting was to have separate fields for each type? not 100% sure though
Okay, just explaining very basic knowledge about programming, so later they can ask normal questions in community
Well let's say that the player can hold 1 weapon at a time - if I would like to add a certain weapon when the game begins, what would that look like?
Could I do something like
SetWeapon(weaponRegistry.GetWeapon(WeaponType.Gun))
or would that be bad practice?
an idea i have would be to have a serialized dict over than enum, so you wouldn't have to add extra fields and logic when adding new weapons, you'd have easy access, and the serializeddict can check for missing enum members if i recall correctly
you would probably want to instantiate the weapons you use beforehand and cache them
oh wait that's just a getter?
hmm kinda
then
Currently have the Weapon assets stored as such
very basic knowledge are still normal questions that should be asked here. asking 1 person is still going to be less reliable
With the game object in question having a WeaponRegistry field, which can gain access to the array of Weapon assets
For example, what is int or why it says void before function name?
yes
what makes these questions not "normal"?
No question is stupid or not normal when it comes to learning :)
So since they are assets of a scriptable object, they are already instantiated, no?
yeah, i was thinking of the spawn you had in a previous example, assuming that would be instantiating some other gameobject from the SO
Ah, I use a separate thing for that, which I called WeaponInstance, which only holds stuff such as durability or whatnot, and type of weapon it is
In this channel people are asking questions based on basic coding knowledge. About systems or tools to use. Less work for you, if they know something, not nothing
i'd assume SetWeapon would take a WeaponInstance rather than a Weapon
it's more work if you explain it poorly or wrong.
this is #💻┃code-beginner
beginner questions are expected
I know answer people will, say. They are going to give link and that's it. I'm using trusted source links to help digest information.
Well yes but for the sake of simplifying the example of how to best gain access to each element of an array of Weapon assets, I left that out, but the question would remain the same - which field should I use in WeaponInstance to reference a Weapon asset?
and noone else in the community can verify your answers.
we can't verify that you used the right links, etc.
and like i mentioned before, no-one i know who's both experienced with a topic and with teaching it would delegate to DMs when they're in a relevant community. so to be blunt, i do not trust that you've given quality help from that
well, a Weapon field?
i may have misunderstood the question, could you clarify
Sorry I misworded - not which field to use, but how to gain access to the Weapon scriptable objects (e.g. Gun) to use when instantiating a WeaponInstance object
2 days ago random guy in community, who I see first time tried to help for hour. Nobody else joined in topic to help, in the end I didn't receive any help or trusted information
If the texture of a gun is stored in the Gun asset from the Weapon SO, how do I gain access to that texture in a newly created WeaponInstance object
you would be using the WeaponRegistry with the specified enum, and then the WeaponRegistry would handle it from there, following single-responsibility
So using a dictionary in the WeaponRegistry, taking an enum as the key and the Weapon object as its value would be a fine way to do it?
yeah, that's what i suggested originally
though i'm not super in the mindset of gamedev at the moment, there's probably better ways
this should be adequate though
Okay perfect - yeah we ended back at where we started haha, but thanks a lot :)
not sure what you want me to do about that.
wouldn't it be worse with private support anyways lol
what's the argument here
Saying, what is difference from stranger asking questions here or in DM. I understand if people like Chris or rob5300 join in discussion
in dm's it's impossible for someone else to join the discussion
if you've provided info and context for the past 30 minutes you will then have to repeat it all when you ask someone else
or if they say something incorrect or ambiguous, no-one else is there to point it out
other beginners lurking or future people searching cannot benefit from the discussion either - ive learned a ton just reading through other people answering questions
ive been in several communities over what, 7 years now? the communities and their prominent helpers all hold this stance for similar reasons. there's a reason these communities exist, and DMs wipe away all benefits
Didn't read the whole convo, but in some cases using enums as indices to an array is a valid strategy.
For example, i'm currently making a tilemap system and each Tile in the map has a TileType enum field.
I then have a TileDefinition[] array of shared tile data that takes the TileType as an index, which is efficient for lookup.
Then I can easily access any tile's definition:
var tile = map.GetTile(xy);
bool isSolid = tileDefinitions[(int)tile.type];```
But this is more of a data oriented design, not something to stress about just yet. Just though i'd point out that what you said initially is sometimes valid
Okay awesome, thanks!
In the ends it's not our choice to make, where they hang out
it is our choice to encourage good things amd discourage bad things
I'm new to unity and I made some player movement scripts, I've added them to the player and they show up on the side but they are not running, can anyone help?
show code
NVM I FIXED IT
I just needed to install some visual studio thing lol
I've been trying to fix this for half an hour and as SOON as I ask for help I find a solution 😭
rubber duck in action
do some debugging - see if the message in question is being triggered, erc
bubber ducky
relatable
I did that before and it helped a lot!
ouch, slow network
fwiw this would not change anything, but it may have triggered a recompile or pointed out a mistake
it probably recompiled 🙏
well it said that the unity thingy was 'not compatible'
so reloading probably fixed that
another possibility could be that you hadn't saved, so keep that in mind (though adding a log and seeing it should rule it out)
alr tysm!
How is find reference actually useful? Is there no way to find only the objects that refer the object directly in an inspector field?
Instead it finds a ton of reference of several orders
Anything that's maybe in the hierarchy of referencing the object
In the r click menu you can "Find references in scene"
You can also find asset references but that uses new search and often takes ages
I mean find references in scence is quite bad. I only want what the inspector directly refers in a field
You are right its quite puzzling sometimes why things show in this search when they dont reference the object/component
But its the only way unless you do your own search by checking all serialized properties
Yea, I can probably make my own editor function to do it. I just wondered if an option like that exist already
Quick question
I'm trying to write a mod for the game "Ultrakill" using Bepinex
But the Update() function is never called, contrary to Awake().
VS mentions that Update() is called every frame, if monobehaviour is enabled.
So my question is; how do I enable it?
you are not using a MonoBehaviour
Here, yes?
yes
When I changed BaseUnityPlugin to MonoBehaviour, my mod would not load
If BaseUnityPlugin already inherits from a MonoBehaviour then this is also a monobehaviour
Which seems to be the case
https://docs.bepinex.dev/api/BepInEx.BaseUnityPlugin.html
What did you change tho 🤔
i wonder
Is the component disabled in the Editor via inspector?
changed from public to private
but the player still doesn't jump
Place a log in Update and first see if it's actually being called
This looks like an xy problem
In normal unity this private/public doesn't matter for Update etc., but maybe it's some quirk in whatever game you are modding
okay, so when it comes to this line
I do notice small screen jerking whenever I press K
Yes
you are making somethign else jump
player is another script, it might be this object that is jumping
I do notice small screen jerking whenever I press K
Sounds like something else is overwriting the velocity next frame
I'm following this tutorial from 2024
https://youtu.be/fL4koeLJ4ko
A Video tutorial on how to make ULTRAKIL mods comment if you want a part 2!
Make sure to Subscribe and like
Should probably consider adding force as impulse since this is in Update
I suggest you to keep the BaseUnityPlugin class really light.
Create a new script Monobehaviour and call it from your BaseUnityPlugin class with something like:
NewMovement.Instance.gameObject.AddComponent<MyCustomScriptMonobehaviour>()
So maybe the game's code changed
And in ur custom script write all the code in your update function
Oh, this is related to modding..
I changed a code a little to experiment and I succesfully set player's hp
Yes, I'm new to modding
and want to mod Ultrakill
You may need to find a more appropriate server for this kind of discussion. This official Unity Discord server doesn't have any channel for supporting modding or decompilation.
I understand, thanks
Can anyone maybe help me add textures to my 3d bear, I’ll give you the download for it and I have a picture on what I want it to look like
anyone know y my Foot IK is greyed out?
this is a code channel, try #🏃┃animation
Long time ago, had issue. and its back. it doesnt save field, goes back to 0. ```public abstract class IdObject: ScriptableObject
{
[SerializeField] public int id {get; private set;}
#if UNITY_EDITOR
void OnValidate()
{
if(id == 0)
{
System.Random random = new();
id = random.Next();
}
}
#endif
}```
You have to mark the SO as dirty which is explained in the documentation for scriptable objects
https://docs.unity3d.com/6000.3/Documentation/Manual/class-ScriptableObject.html
I'm trying to deal damage to an enemy in my game, and I keep getting this error
does anyone know how to fix this?
yeah i've fixed this error hundreds of times. you gotta show what's on line 21 in EnemyBulletTouch though
here's the code I'm using!
which one is line 21?
collision.gameObject.GetComponent<Enemy>().Health();
under the if statement
left image
so the gameobject doesnt have the Enemy component then
this is my first day of unity so bear with me but what does that mean 😭
did you put the Enemy script on your enemy?
Hey, so if I have a player that has 2 stats regarding movement, speed and acceleration, how do I make the player follow the mouse cursor on the X using that?
I think Vector2.SmoothDamp could be good here but I don't know what should go in the smoothTime parameter.
Here's what documentation says about smoothTime
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Vector2.SmoothDamp.html
I personally would take the mouse position and just use Vector2.Lerp(). Here's a related discussion page: https://discussions.unity.com/t/make-object-follow-mouse-2d-game/520226
so should smoothTime be speed / accel?
Hold on, lemme get on unity and test it out
alright, may i take a look at your current code?
using UnityEngine;
namespace AOR.Core
{
public class Bowl : MonoBehaviour, IBowl
{
public float Position
{
get => transform.position.x;
set {
var p = transform.position;
p.x = value;
transform.position = p;
}
}
public float Target
{
get => target.x;
set => target.x = value;
}
public float Velocity
{
get => velocity.x;
set => velocity.x = value;
}
public float Speed
{
get => speed;
set => speed = value;
}
public float Acceleration
{
get => accel;
set => accel = value;
}
public Vector2 target, velocity;
public float speed, accel;
Vector2 RealTarget
{
get => new(target.x, -3.5f);
}
void Update()
{
transform.position = Vector2.SmoothDamp(transform.position, RealTarget, ref velocity, speed / accel, speed);
}
}
}```
i didnt get it to track player movement just yet, still trying to figure out why im not getting input actions
nvm found it
You want Vector3.MoveTowards()
using lerp to keep moving towards some position wont work well
Lerp can be used to animate from a to b over x time
Too many beginners use Lerp incorrectly
i dont think im using lerp here?
or is SmoothDamp using lerp?
You arent but I am warning you about what others said
smoothdamp is not the same as lerp
yeah I know
1 - Mathf.Exp(-Time.deltaTime * speed)
Does this look sort of like the intended behavior?
Yeah for sure (myself included lol)
yeah exactly!
Awesome! What I did is just took the mouse position and turned it into its world position, and assigned that as the target. I did change a few things from your file since I have no idea what AOR.API or IBowl is, shouldn't make too much of an impact. Here's my code
using UnityEngine;
namespace AOR.Core
{
public class Bowl : MonoBehaviour
{
Vector2 mousePosition;
public float Position
{
get => transform.position.x;
set
{
var p = transform.position;
p.x = value;
transform.position = p;
}
}
public float Target
{
get => target.x;
set => target.x = value;
}
public float Velocity
{
get => velocity.x;
set => velocity.x = value;
}
public float Speed
{
get => speed;
set => speed = value;
}
public float Acceleration
{
get => accel;
set => accel = value;
}
public Vector2 target, velocity;
public float speed, accel;
Vector2 RealTarget
{
get => new(target.x, -3.5f);
}
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
target = mousePosition;
transform.position = Vector2.SmoothDamp(transform.position, RealTarget, ref velocity, speed / accel, speed);
}
}
}```
btw im a beginner as well, there might be a better way of doing this, I'm not sure.
anyhow, im gonna get going, have a nice one
Oh now i understand, looks good bar the use of a property for RealTarget
i did some major changes to it over the hour
completely redid the target code
void OnTriggerEnter(Collider target)
{
if (target.CompareTag("Enemy"))
{
BasicSkeletonEnemyScript EnemyScript = target.GetComponentInParent<BasicSkeletonEnemyScript>();
int output = EnemyScript.Health - damage;
Debug.Log(output);
}
}
}
im a beginner scripter but im stuck because the script doesnt give out any errors but it doesnt print anything either. If i make a different debug.log and put it outside the if statement it prints
i dont know what im doing wrong since the enemy has the "Enemy" tag
!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**
Tysm
does it have the Enemy tag or enemy layer?
enemy tag
Idk how to do that
is the tag on the parent or the collider object?
yes thats the purpose of that
not this server
there is no collab or job posting here thats what the bot message is telling you
How do i like what do i do
its against the rules of the server, so go there
the enemy is an empty object that has an hitbox child that has the enemy tag
basically
the object with the collider should have the tag
I think im special
ohhh alright ty
H e l p
@last stone Stop spamming the channel
Wdym im not
!mute 1336499403988668481 3d spam
@noshoustherealone muted
Reason: spam
Duration: 3 days
how do i get an object's rotation info and run an if statement if the object is upside down?
and to check if it is upside down there are many ways on how to do it, one way is to check the transform.up < somevalue
sorry, this was a little misleading. i have two scripts for the mouse movement, the Horizontal for the Player (parent) and the vertical for the Camera (child) and i want to access the X rotation from the camera and if it's upside down ( >180) i want the x mouse to be inverted
would clamping the values not be a better approach?
i purposely did not add clamping
ah okay
it's a mechanic in the game i want to create
Any suggestion before i switch my 2D player float movment to int movement to be pixel perfect
impossible, quit while you are ahead
not really measurable
Oh
OH WELL
Illl do it anyways
I have a procederal generation code and a navmesh ai. How would I get the NavMesh to affect everything thats been Prodecerally generated.
you would have to rebuild the navmesh after generating
How would I do that?
Unity is the ultimate game development platform. Use Unity to build high-quality 3D and 2D games, deploy them across mobile, desktop, VR/AR, consoles or the Web, and connect with loyal and enthusiastic players and customers.
Thank you
if im going to tell you 1, will you try it out?
i want sombodies 2D game experience
I am already doing coding so like
It could be 1 or it could be 10. Depends on what you're doing
Alright, so I'm finally at one of the cooler parts in my game. Ability making! Yay!
Only thing is that I'm not sure how I want to structure this. I have a base Ability class. I know I want that. But when constructing other abilities (assume that they are going to be unique, so something like scriptable objects won't necessarily work for them all), do I make a bunch of scripts for each ability that inherits the Ability class, or do I make like a super script that constructs all the abilities?
I guarantee inheritance is a bad way to approach this.
Look into composition instead
i.e.:
class Ability{
string name;
List<Cost> costs;
List<Effect> effects;
}```
Yeah, started to think inheritence was a bad idea too
Yeah and then from there just do new Ability() in some "ability builder" area
possibly, or make it all serialzable and edit in Unity
or use spreadsheets or json or yaml
Gotcha, what would you recommend? I'm just curious, I think I'll do manual building in code right now
Gotcha, thanks for the help!
Thinking about how I want to make abilities "do their thing" in an elegant way. This is what I got at the moment:
using System;
using DataStructures.Enums;
public class Ability
{
public string abilityName;
public int actionPointCost;
public AbilityActivationType activationType; //To do: vague/too general. iterate on this more
public Action<AbilityContext> activationBehavior;
public void Activate(AbilityContext context)
{
if (activationBehavior != null)
activationBehavior.Invoke(context);
}
}
The main thing to look at is activationBehavior and Activate(), but any feedback on the rest of the stuff is welcome.
Currently, AbilityContext is just a basic Object class that contains who is activating the ability and who they're targetting.
The idea here is to hopefully allow myself to specify what abilities should do when building them while still activating them in a centralized way
Composition is the best way to do things usually
The largest problem with ability systems that I do have is targeting. Usually the most top defined behaviours will include them but can ultimately split logic if not done correctly.
Now that I'm piecing things together a bit more, I think scriptable objects are kinda goated for this
Being able to visually see what's been built is nice
I don't know if you've modded xcom 2 before, but it has a pretty good system for targetting. Most of my work here is based off of their ideas, but translated to unity (easier said than done O.O)
Some of their stuff is kind of dated though, like the event system. I'm warming up to unity's a bit more
And the obvious fact they're using unrealscript XD
So no dictionaries for example
Consider using event for the activation Action. You can also do ?.Invoke(blah); to safely invoke if not null
I think I came up with a more robust idea. I have the ability execute an array of effects, which do the real logical heavy lifting. I'll put up what I have now
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Nice thing about this is I can iterate on this pretty nicely. Effect priority, other, optional functions that can be added to AbilityEffect, or more abstract functions
Oh, and it all loops into ScriptableObjects, so if I want to reuse effects/abilities, I can do that without any code
how do i get my visual studio to appear like this?
mine is the second picture, its missing colors and it often autofills incorrectly
!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
how do i assign a button ?
what component is that?
nvm the tutorial i followed was misleading
how can i change cameras mid game with v? the tutorial i followed didn't mention how to bind a key to this action
You need a update function checking if a specific key(s) was(were) pressed in the update frame, if so then call your desired method for that key bind is the simplest
well i was asking how can i check if a key is pressed because everything i tried failed
Did you try the if ( Input.OnKeyDown(KeyCode.V) ) inside a update method in a class that's live at runtime?
wait lemme try
Might be OnKeyUp, I don't remember I use a custom class I made for key inputs
I believe that's also legacy input however for that method in general
OnKeyDown does not exist in Input
Yeah thought as much
are you not using the new input system?
Add import UnityEngine.InputSystem
i use both
vs already added this
Then check if(Keyboard.current.vKey.wasPressedThisFrame)
if ( Input.GetKeyDown(KeyCode.V)
That should be correct I believe
that didn't work
maybe the methods are the problem
No, that's just old input system
Your methods are fine
lemme try this
you said you are using both, so what i posted should work
nothing works
It won't if a newer unity version template was preloaded with the new input system, I had that issue initally
What is the error?
no errors
Show me the class?
nothing happens when v is pressed
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.UI;
public class CamViewChanger : MonoBehaviour
{
public Camera firstPersonCam;
public Camera thirdPersonCam;
void Start()
{
SetToThirdPerson();
}
void FixedUpdate()
{
if (Keyboard.current.vKey.wasPressedThisFrame)
{
if (firstPersonCam.enabled == true)
{
SetToThirdPerson();
}
else
{
SetToFirstPerson();
}
}
}
public void SetToFirstPerson()
{
thirdPersonCam.enabled = false;
firstPersonCam.enabled = true;
}
public void SetToThirdPerson()
{
firstPersonCam.enabled = false;
firstPersonCam.enabled = true;
}
}
Attach the script to your player object
the start part was to test if the methods are working
already did
Does it go to third person when you load scene?
How can I show code in here
Can you add a debug.log to the Start() and see if it pops up in console?
!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.
Fuad for user input you need to use Update instead FixedUpdate
unless you want to spam the key to catch the input you would have to go for Update
True, Start isn't being called regardless though so I don't think player object is being initalized or "started with" in anyway lol
There's no command called
code using.
Oh my
@zinc zenith Make sure your embeds display is turned on and read the bot message how to post #💻┃code-beginner message
You might want to delete that duplicate audio listener event too just fyi
How can I make embed display
Wrong symbol, copy/paste the example from the bot message
Oh I'm blind as hell
@brave token in your settothirdperson method you set first person cam twice
Make sure the second boolean is the third person boolean
using UnityEngine;
public class BulletHit : MonoBehaviour
{
public GameObject enemyPrefab;
public string enemyTag = "Enemy";
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(enemyTag))
{
Destroy(other.gameObject);
Debug.Log("Enemy is Dead");
}
}
}
@zinc zenith You can delete or edit your messages as well, don't leave the spam
Also replace your fixed update method with this
void Update()
{
if (Keyboard.current.vKey.wasPressedThisFrame)
{
if (firstPersonCam.enabled)
SetToThirdPerson();
else
SetToFirstPerson();
}
}```
It's cleaner
it finally works thanks
using UnityEngine;
public class BulletHit : MonoBehaviour
{
public GameObject enemyPrefab;
public string enemyTag = "Enemy";
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag(enemyTag))
{
Destroy(other.gameObject);
Debug.Log("Enemy is Dead");
}
}
}
That's all the code
What did you need clyde
I want the player to not disappear when the bullet hits the enemy
@zinc zenith #💻┃code-beginner message
Is your main player tag also enemytag? Lol
@zinc zenith Not deleting the spam after you again. Clean it up or I will time you out.
Shouldn't matter because the collision isn't hitting the player but
I have never post code in here before
Main player tag is player
Also are you talking about the enemy disappearing or your own player
Just confirming
Does your player also have a method to delete yourself when hit with a bullet?
Or 'die'
No
can you disable the BulletHit script for a second and test if it is working as you want
If your player shares the same collider as the Enemy object you will also be deleted. E.g player has a child named "Enemy"
Is the enemy's tag enemyTag or enemy?
Enemy
Damn I didn't even notice that lol
Id presume the cause was your "player" having the Enemy tag
Try putting enemy instead of enemyTag in your script
He already said this wasn't the case
guys dont forget he is using 2 different scripts he has them on both objects it seems
Or try putting a logical gate like
if (other.CompareTag(Enemy) && other.CompareTag(!Player))
😆 why
Just in case
This is beginner chat man, no need to be aggressive lol
Beginners trying to help other beginners leads to this 🤷♂️
It worked for my script
Another project
perhaps TagHandle has some funky way to use this operator but otherwise no
Well I had already asked if he was sharing the same script or collider on the player as the Enemy object and he said no, and no script for his player to even die, hard to debug without seeing his scene hierarchy lol
Let me send my screen hierarchy
@zinc zenith let me see your scene hierarchy while in runtime before you shoot anything
Will help
Also show the console
Its possible I guess ive seen crazier things here
WIN + Shift + S
I can't send recordings because they tend to be too big for discord normal
I don't have nitro
Then record it at a lower quality or a lower fps
Aight
Make sure to record to mp4
this server is boosted and has 100mb upload limit
Maybe he's recording at 4K 120 fps or something
Hey, guys! You know I have a problem. I have a locked icon on my game and an interaction icon as well, so when the player detects a locked door locked icon is being displayed, but for one reason I do see the locked icon clearly, but I can see also barely the interaction icon at the same frame. Probably something is happening here with the detect locked door method i have.
{
if (IsDoor(hit.collider.tag) && IsLocked(hit))
{
interactHUD.SetActive(false);
lockedIcon.SetActive(true);
}
else
{
interactHUD.SetActive(true);
lockedIcon.SetActive(false);
}
}```
Could you please help me?
shouldn´t the second part also be hit.collider.tag , you only have hit there
IsLocked probably checks the lock state of the hit object so should be fine
And the order of operations looks fine.
So.. so long as your cursor is over the door, the icon appears? It could be due to the script that detects/displays the initial icon.
As long as by cursor is over the door it is being displayed properly, but when I move away my cursor and then move it again over the door it does this thing
I feel like too much information is missing to judge what is wrong...
thats why I am thinking maybe it has to do with the frame
What do you want to happen?
probably
so at the frame where I move away and then again point over the door at this frame probably
If you are doing this raycast each frame then shouldnt matter
For this other icon to be revealed then a raycast needs to be performed, hit something and this must not be a door and not locked
Also the else block is not executed if your raycast doesn't hit anything, should it?
I pointed that out just now yes BUT we have no idea do we?
fuck knows what happens to get to this function
Do you want me to share my raycast logic?
yes
or we can guess and get no where 😆
An important skill to develop is being able to "walk through" your logic and deduce what is happening
If you can do that you can also see what other things need to be shared for others to help
e.g. the raycast performed prior to DetectLockedDoors() being called
if (raycast)
{ do something; }
else
{ do someting else ; } //this part is missing
to visualize what rob and aleksiH already pointed out
I think I found the issue give me a second
I am using layers for 3 different types
just give me a sec
I could be wrong but do you have 2 seperate scripts trying to control the cursor/icon?