#💻┃code-beginner
1 messages · Page 68 of 1
Damn, one schools teaches fun stuff like Unity, another one teaches using prehistoric systems and office
I guess I'm somewhere in the middle
well mine was years ago though, things have drastically changed since then
im talking 2008
Makes sense
i have a question and i need you guys to be brutally honest
thats my forte
Is it wrong that sometimes, when im desperate i ask .ai for help or to explain me things?
(code speaking)
I do not think it's a good idea.
agreed
You'll get plausible looking answers
it can do more harm than good without you knowing it because of this ^
but this doesn't mean you'll get valid answers
people with experience can notice this, but you're asking because you don't have experience!
It can give you correct info , the problem is you have to tell when it is and when its not
it's good for general c# questions but asking it to write you a script of game logic is not
So its alright as long i dont do it anyways and try to understand how it works?
(it's more trained on some documentations than others and it doesn't seem to be for unity)
no you should back up what you found out by simple internet search
I'd say it's not a good idea, but if you kinda know what you're doing them AI just might give you a slight push by generating that one line of code that you've been wanting to use
and see if it matches what you read on AI
ooohh. okay
ooohh, double okay.
My experience for using it with unity is it grabbing the first stackoverflow post and posting that answer
the what
is there a builtin function for flipping sprites vertically?
ahh this good ol site devs used to use (its a joke its still popular)
rip 😦
in what context? SpriteRenderer has a flipY property
im making a gun sprite that pivots around the player sprite in 2d and i want the sprite to flip once the angle reaches over 180 degrees
where you should be looking a lot for Dev/coding
https://stackoverflow.com/
You made it sound like the web was dead 💀
nah i was jk, because before AI everyone knew you go to StackOverflow 😛
the name itself gives it away what its for
A beginner won't know what those three words together are ;p
thast true xD 😭
question is how would i assemble this statement
if you get a Stack Overflow in unity You done fdup heavvy somehow 😆
yea
dont need it colliding
sprite and rigidbody2D are two totally different things
I hate flipping in 2D because the pivot is still wrong direction
StackOverFlow, i think i have heard of it before but i dont know that that is.
I just rotate the object 180 on Y
since unity is 3D
this way my transform.right is always correct
flipping in 2D is very easy. But I usually change my scale, and not .flipX
isn't the sprite then upside down?
in 2D rotating on Y would flip it from right to left
right, yeah
it'd come "towards" the screen as it rotates, if it's not an instant rotation
yeah it would look all skewed lol
scale.x *-1
its usually when I strictly want the 2D physics/light engine
otherwise i just use 3D objects with sprite renderer
navmesh is less of pain to deal with
unity gives free a* for 2d pathfinding. Not sure if they removed it
So you dont need navmesh
where would that be? because I never found such a thing
gimme a sec
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SeedHolder : MonoBehaviour
{
public int seed;
public int xPos;
public int zPos;
public List<GameObject> Rooms;
public GameObject Logic;
public GameObject newRoom;
private bool isTriggered = false;
private void Start()
{
Logic = GameObject.Find("Logic");
Logic.GetComponent<RoomHolder>().Rooms.Add(this.gameObject);
}
private void OnTriggerEnter(Collider other)
{
//Load Room X + 1 & X - 1, & Z + 1 & Z - 1
//Unload Rooms where X > X + 1, X < X - 1 & Z > Z + 1 & Z > Z - 1
if (other.CompareTag("Player") && !isTriggered)
{
foreach (GameObject Room in Rooms)
{
SeedHolder seedHolder = Room.GetComponent<SeedHolder>();
if (seedHolder.xPos - xPos > 1 || seedHolder.xPos - xPos > - 1 ||
seedHolder.zPos - zPos > 1 || seedHolder.xPos - zPos > - 1 )
{
Destroy(this.gameObject);
}
}
if (Rooms.Count < 10)
{
if (xPos - 1 >= 0)
{
GenerateRoom(xPos - 50, zPos);
}
if (zPos - 1 >= 0)
{
GenerateRoom(xPos, zPos- 50);
}
if (xPos + 1 <= 9)
{
GenerateRoom(xPos + 50, zPos);
}
if (zPos + 1 <= 9)
{
GenerateRoom(xPos, zPos + 50);
}
}
isTriggered = true;
}
}
private void GenerateRoom(int xPos, int zPos)
{
Vector3 rotation = new Vector3(xPos, 0, zPos);
Instantiate(newRoom, rotation, Quaternion.identity);
}
private void Destroy()
{
Logic.GetComponent<RoomHolder>().Rooms.Remove(this.gameObject);
}
}```
navmesh is A* anyway
ok hold up
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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 mean a link would be preferred..
Link to the code?
yus
I suppose I could put on git, Ill try
tada
so why git lol you got like 5 quick options
like that?
yea
you mean GitHub?
Ye
whats the question again?
presumably you're talking about making a Gist on GitHub
what's the issue? Freezing?
I suppose you could commit your work, push it to a website that hosts your git repo, and then send us a link
I would guess you're spawning a room and that room is instantly spawning another room and so on
I feel like yall really giving me heck when I immediatly did the thing you asked XD
my bad
so im making a 2d topdown shooter and im wondering what method of doing this would be best
im rendering the player body and player hands as two seperate objects, both of which are rigidbody2ds.
the player hands arent gonna have collision, is it worth using a dynamic sprite instead?
dies internally
there's no reason for the hands to be a Rigidbody from that description
wdym dynamic sprites? you mean bones? 2d IK?
not sure what "dynamic sprite" means
Infinite spawn issue
not sure but im seeing these and they might work
I would guess that each room is triggering the other rooms to spawn
oh weird, I never noticed that
Rigidbodies are for physics.
Sprites are for rendering.
These are two completely unrelated concerns.
PLEASE help me ! I beg you (🤣 )
Camera_Manager.cs(127,87): error CS0070: The event 'TerrainManager.TerrainGenerated' can only appear on the left hand side of += or -= (except when used from within the type 'TerrainManager')
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.
I cannot understand and solve this error.
TerrainManager.TerrainGeneratedHandler terrainGeneratedEvent = TerrainManager.TerrainGenerated; this line of code is nonsense
you can't assign an event to a delegate variable
as the error is saying
what are you trying to do here
I tried the invoke, I tried all the usual ways
Do you know what event means?
I'm starting a ritual
throwing random stuff at the wall won't fix your problem
It means the delegate can ONLY be invoked from the class that owns it
you are trying to invoke the event from a different class
it doesn't work that way
either:
- get rid of the
eventkeyword - make a public function on TerrainManager that invokes the event and call that instead of trying to invoke the delegate directly
I often do something like this:
public event System.Action Florp;
public void DoFlorp() { Florp?.Invoke(); }
Hi,
I have a wierd error that I havent come across before.
I have set up a prefab and a runtimeIntilizeOnLoad on a static class so that all my necessery objects are loaded no matter what scene I use. This is all working as inteded.
However when I load a scene for a second time it seems like these cant find in the scene.
I have a simple funtion
GameObject.Find("playerParent").transform)
that is beeing called when
(SceneManager.GetActiveScene().isLoaded)
This works the first time the scene is loaded but not the second.
I have never had this problem before and therefore im thinking that the fact that I use the runtimeInilize somehow is to blame
do you have any idea why this raycast doesnt detecte the ground ?
not witout seeing some code
I should also say that i can find the "playerParent" in the inspector but I still get a null refference error
https://gdl.space/omewafaxov.cs https://hatebin.com/hskwioauto Could anyone help me figure out why my stat calculations are not working in my Character Class? It is only pulling the stats from the base class and not performing any calculations based on the vigor, agility, wisdom, strength, dex, and int. Thanks
it work on my scene just with a plane, but not in this more detailed scene
use Debug.Draw ray and debug your raycast
so you can see where it is
did you read my code ? 😭
yus
yes, floors are all mesh colliders
Debug.Log(hit.collider.name);
oh, it actually detects it
guys I am starting game development right now
I followed a tutorial to make this movement script but when I try it on unity it has a visible input lag... is it normal?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public float moveSpeed;
private bool isMoving;
private Vector2 input;
private void Update()
{
if (!isMoving)
{
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
if (input != Vector2.zero)
{
var targetPos = transform.position;
targetPos.x += input.x;
targetPos.y += input.y;
StartCoroutine(Move(targetPos));
}
}
}
IEnumerator Move(Vector3 targetPos)
{
isMoving = true;
while ((targetPos - transform.position).sqrMagnitude > Mathf.Epsilon)
{
transform.position = Vector3.MoveTowards(transform.position, targetPos, moveSpeed * Time.deltaTime);
yield return null;
}
transform.position = targetPos;
isMoving = false;
}
}```
p.s. feel free to ping me after answering
hi i have a problem. i am making multiplayer game using netcode for gameobjects. i want to share server with developers, so they can test the game. how can i let they connect to server?
Yes, it's designed to accept new input only after the character has stopped moving
no one writing on this channels
oh, okay. But is there a way to make it avoid this problem? I am not very good in cs 😅
Anything is possible but that's going to be a bit more difficult
click the Pin in the channel
the NGO server is active
fantastic 😂 I'm gonna work on it, thank you for your help
bump
no
Okay \o
I'm not seeing where you're updating your UI here or where you're grabbing these values to display, but you do have methods that returns the calcs, so make sure those values are correct and you're calling them.
let me add the script that updates UI
public Character(CharacterBase cBase)
{
Base = cBase;
//this.Level = level;
currentHP= MaxHealth;
currentMana= MaxMana;
//Generate spells
Spells = new List<Spell>();
foreach (var spell in this.Base.LearnableSpells)
{
if (spell.Level <= this.Level)
{
Spells.Add(new Spell(spell.Base));
}
}
}
Have you debugged your values here, and that currentHP is being set to new values?
rather, your desired values
about to do that, sorry working on this inbetween projects at work lol
The code looks fine honestly
- irrelevant
- not true
hey guys. I already managed to change the instance created color, but I am not being able to do the same with the text, any ideas?
And what does the error say?
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
ok I see your problem. So, in your constructor
additionally, logging hte other stats, they are also not being updated
Yeah, you dont set your other stats after adding your scriptableobject in your constructor
either read directly from the SO, or set the variables in your character class as the SO base values
Over is not text, right? It is the class OverHeadDamage...
the SS isnt the same as sending it like that? https://paste.ofcode.org/9mHspc2eTrDHttiWA9vhtX
It is not
its the instantiated object
Exactly. So it doesn't have a text property
it gives me the option when I tipoe over. it gives me text
So you made a text property on the class?
I am all day just to create a simple critical damage thing.. my neurons are already burned out
basically you can remove all this from the character class
int vigor;
int strength;
int dexterity;
int wisdom;
int intelligence;
int agility;
and instead make your calculation properties as:
public int MaxHealth
{
get { return Mathf.FloorToInt(Base.HP + (Base.vigor * 5)); }
}
use string interpolation
Ah, text is the text COMPONENT property on OverheadDamage
So you need to do over.text.text
Poor naming, which caused confusion
oh, but if you want to add vigor over the base stats, then you would keep it there
yeah keep those variables, but set them from the SO in the constructor
So my concept is upon level up, the stats in your screenshot can be increased by player choice (get points to put in). I didn't think i would want to update the baseclass
You're right, if you level up and have more vigor you want those variables
so, technically your calc methods will look like this:
public int MaxHealth
{
get { return Mathf.FloorToInt(Base.HP + ((Base.vigor + vigor) * 5)); }
}```
maybe name your non-base variables like extraVigor,
true. omg i wish I could be so good as u guys.. u spoted the prob and u cant even see the whole thing.. I am so dumb
thank you a lot
You are the fricken man.
yee
so i should probably do that for each int get on this character.cs
Nah you're fine! We all make mistakes. And they are often easier to spot from the outside haha
Maybe.. sometimes maybe looking to the same script hours and hours we get blind to some stuff. THank you
and I renamed it ```cs
over.overHeadText.text = "" + _playerBulletDamage / 2 * 2;
won't that still give you a compile error?
oh nvm
/ and * have higher precedence
I was imagining it was going to try to divide a string by 2 :p
@timber tide Do you think it would be wise to make current values for each of my stats and then set them to = that stat, like i did with Health and Mana,
depends how you want to do it
you can read once the SO and set values from it, or make your variables add extra values like I did above
is that an SO?
it cuts down on a step if you always read from the SO though when you deserialize everything
if this code is in an SO, then that is a bad idea
it would need to be separated into a separate non-SO class
it's a plain data class
Sorry im still pretty new, what is SO
scriptable object
scriptable object
ah
is maxHP like a constant? or is it a system where it changes like in a JRPG
then i would do it like how you have, except make those properties have private set
help I dont know why my procedurally generated rooms are so small now
you don’t want random classes being able to modify these externally willy-nikly
Well, i would want a class to be able to modify it when i get a level up i would think
but i could be thinking about this wrong
property fields are kinda methods in a sense
object oriented programming is inherently dangerous, so you want to really restrict access to changing things as much as possible
just need to expand the logic out on them instead
I also happen to be designing an RPG-y stats system right now
You need to draw a line between the data that changes and the data that doesn't
Suppose a Fighter has a base strength of 10, and also gains 2 strength per level up
whenever you change currentHP, that would need to be coupled to checking death etc… There should be a public method for changing currentHP that handles any logic for changing chrrent HP
Suppose you then update your game so that the Fighter has a base strength of 15 and gains 1 per level up
If you just stored the strength stat directly, your old save games would now be bogus
you'd have the wrong numbers
in pokemon, you’d need to not just change HP, but change the color of an HP bar, start/stop playing near death music, change pokemon’s animation from being hurt etc
you don’t want external classes to just straight-ass modify currentHP
indeed
not because an evil hacker will change the HP
so all of these should be private?
but because you want to control how the data is changed
public int myInt {get; private set;}
yeah, public getter + private setter is very useful
thenever you allow public set, you better know wtf you are doing, because that shit can go south real fast
private float currentHealth;
public float CurrentHealth
{
get { return currentHealth; }
set
{
if (value > maxHealth)
{
currentHealth = maxHealth;
}
else
{
currentHealth = value;
}
}
}```
Like something like this instead of methods is fine too.
I do like just making methods though
i would make it private, and make public void ChangeCurrentHP(
either way, it's exposed one way or another
unless you bind some delegates if you wanted
not totally exposed. we’re separating misc crap that needs to happen a bit more
and if you just call currentHP = 5; that doesn’t really convey that you have more going on under the hood
or interact with it through things like public void GetHit(Damage amount) { ... }
yeah
You can still have methods that directly adjust your health
But you want to use the right tool for the right job.
I would also make public event Action OnHealthChanged;
so other things can know if something just changed
this, but I typically pass the amount too
delegates probably the best way if you really don't want it to be touched
yeah i havent really gotten all the way to that part yet, just getting my initial values set right now
and set through a constructor
incase they need to know for some reason
and values that can influnces those initial values
Action<int> OnHealthChanged
or w.e
you need to really protect it
i can’t stress enough how much you want to restrict that value’s exposure
I wouldn't worry too much until you're set on the logic and scope
it protects you from yourself :p
i have made a generic of this if you want, I think
sure, i would love to see it to compare
Like, if you've been using unity you're forced into a dependency injection pattern anyway, which already kinda screws with these methods
you don't always have the privilege of using a constructor, so that removes a lot of variables you'd otherwise set as readonly.
this does allow the set to be fully public
in using it, you would: public ReactiveValue<bool> myBoolean { get; private set; } = new();
this fully exposes the Set for anyone, but also calls the event for anything listening to go off
in your case, you would want something similar to this, but it would be inside of the definition of the class where you are using it
example (with private set):
I wouldnt exactly say you're forced to use DI in unity, I feel itd be the opposite. In stuff like web dev there is no way to find other components so that's why certain patterns like DI or factories are more common
how do you deal with multiple controller inputs, and how do you link an input to a player actor?
@pulsar lodge understand?
You're forced in a sense that if you're inheriting from a mono that unity will call the base constructor, so you're usually relying on start() or your own initilizing methods to populate your variables.
i wouldn't say that's "depednency injection"
or that it forces you to use it
but then again, DI is literally just passing arguments to something
dependency injection is a shitty name tbh
well, it sets you up for DI which is actually convienent because pooling gameobjects is ideal
i think i do lol. Sorry i am such a noob. I've dont have a ton of experience yet and Unity feels like a whole new world to me, can be a little overwhelming to take it all in at once. School has not prepared me for this haha, most of my stuff i've done has been 1-2 class projects.
Isnt there a better way to make an animation playing from an animator to stop beside using animator.speed ?
you might want to look into godot while you’re very new
unfortunately this is for a class, otherwise i probably would lol
Yea that's definitely not DI. DI would be more like some other script (which likely creates your monobehaviours) will plug in any references that it needs. Im not sure if unitys whole "drag and drop reference" thing can be classified as anything. Maybe dependency inversion depending on how u code it but im not too knowledgeable on all these jargon terms
I dont know if You can still help me.. but it gives me object reference not set to an instance of an object error in the on trigger inside the if and else. https://paste.ofcode.org/MFfFFmQtdQYphFdCzjxiLt
I really appreciate all the help @buoyant knot @timber tide @swift crag
from what I've gathered, this is DI:
public int AddTwo(int x, int y) => x + y;
because you give AddTwo the numbers instead of making it make it up its own numbers
just put it in a different state?
i don’t think so
I've found it very hard to nail down any more meaningful of a definition
I'm not familiar with all the terms either, but I see DI passed around with Unity and from just reading on the pattern(s) I feel like that's the most relevant term for it?
Not really because the script does not depend on these values. The script doesnt even use these
dependency injection is when you have A=>B, and then you change it to A=>C<=B
=> is depends on
real DI when you do it in console apps xD
of course it uses them. it uses the values of x and y to decide what to return!
most dependency injection is using a base class or interface
maui flashbacks
the classic example of DI I always see is turning this:
public class Foo {
public void Bar() {
Logger logger = new ConsoleLogger();
logger.Log("Hi");
}
}
into this:
public class Foo {
Logger logger;
public void GiveLogger(Logger logger) {
this.logger = logger;
}
public void Bar() {
logger.Log("Hi");
}
}
therefore DI means "give something an X instead of having it figure out its own X"
Actual DI would be like the script is for enemy movement, but it needs the settings for like how tall/wide the AI is. You create that enemy movement script and plug in the settings through some init method
so I have these "arena wall" sort of things that disappear when there are no enemies left in it, but I dont really have a way of ignoring the player in this.. any suggestions?
It just seems like a borderline tautology to me
DI is when you give something values
Try using the attachment service at https://www.patreon.com/codeaesthetic
You'll also find deleted scenes, song names and more
if you want to have a count of anything put them in an list/array
In unity that's probably a fair description, although I'd still argue the int example isnt DI since the script is just being used as a calculator. It is not using the "injected" values at all, doesnt even store them
True DI is overkill for unity imo
The operation being performed is irrelevant
OnTriggerStay is not the right thing to use here.
Use OnTriggerEnter/Exit, or a direct physics query, and keep a collection of the enemies so you know how many there are.
HashSet<Collider2D> enemies = new();
void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Enemy")) {
enemies.Add(other);
Debug.Log($"New enemy count is {enemies.Count}");
if (enemies.Count == 1) {
Debug.Log("No longer empty!");
}
}
}
void OnTriggerExit2D(Collider2D other) {
if (enemies.Remove(other)) {
Debug.Log($"New enemy count is {enemies.Count}");
if (enemies.Count == 0) {
Debug.Log("Empty!");
}
}
}```
well yeah but here's the thing I have enemy spawners
microsoft's di
public static IServiceCollection AddSingleton<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TService>(this IServiceCollection services)
where TService : class
{
ThrowHelper.ThrowIfNull(services);
return services.AddSingleton(typeof(TService));
}```
😵💫
wow yeah Im glad I came here Im just gonna yoink that code thank you-
I've just never really been convinced that DI is some specific pattern or design philosophy
maybe this is just a matter of semantics
and sometimes I look at the Zenject README and my brain explodes
(oh my GOD it's so long)

Each spawner should be associated with a specific wall.
Anyway, my example of bringing up DI was just to show that you can be stingy with access modifiers since inheriting from monos does not allow you to set otherwise private data in the constructor. You can of course set it through the inspector if it's serializable, but otherwise use plain data objects if we don't want these variables to be accessable.
the spawner should tell the wall about every enemy it spawns
wha-
when the spawner is done spawning enemies, it should tell the wall that it's done
then, when every enemy has been destroyed, the wall can disappear
Im.. confused what-
can we just agree public fields are bad?
I mean it kinda is. I cant just call a method, giving it some int=0, it does nothing with the int and say I'm doing DI. Calling any method at all would be DI by this reasoning, making it not even a pattern
its- its never done unless the player destroys it-
precisely (:
there's no need to be dramatic
just correct me if I've made an incorrect assumption
Explain to me how your game works.
and I dont want the walls to disappear if there are enemies inside still
I.. didnt think I was being dramatic, sorry
"its- its" "wha-" reads fairly dramatic
Just to explain
But yeah, hard to tell it text
it sounds like how i'd write a character breathlessly stammering in confusion :p
anyway. explain to me how you want the game to work.
hey guys how can I have access here to change the text? I already have access in my class to this component, but I am not being able to change the text.
What is causing the nullref?
yeah Im okay Im just going to yoink this once again thank you
over.text.text = "" + _playerBulletDamage / 2 * 2;```
Iirc you had a Text field. That is TMP_Text
why is it text.text
I just want to change this text
'cos the field is named text
Ok yeah, you're trying to get Text, but that is the legacy component. You need TMP_Text
I do that a lot
i will change the name as soon as it is working
why is bullet even caring about text
The Type is the real issue
textDisplay.text 😏
how to reverse a game object's velocity
-
yeah but how can I change the text here?
will try
what if it's -1 already
its not like a copy and paste code, I was just suggesting the name would be probably more implicit what it is
you must have a reference to this text component
so whatever over is has a field called text
I have no idea what that code looks like
over is just the instantiate object
show us the code that defines whatever this over object is
ho sorry i posted the code sometimes above while others were helping me.. here it is again
you've already been told
the - operator negates something
so just speed-; then?
no, the unary minus operator is a prefix
int x = -3;
e.g.
x = -x; would flip the sign of x
I need to see OverHeadDamage
the hell
You change the type to TMP_Text in OverheadDamage. That is it
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
is something unclear?
will try thank you
idk what to use at this point
all of this just a simple ping pong game
i have said that you should use comparetag instead of ==...
and i can't make the ball move
At this point show the code you have
It's as simple as using a -
Rigidbody2D rb;
public float Speed = -1f;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
rb.velocity
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Player")
{
Speed = -Speed;
}
}```
i tought it was the simplest i've ever done
didn't finish
What is going on in Update?
You seem to have not finished typing your line in Update
yes i didn't finish yet
cause idk what the hell to do
tried ussing add force
it flew out
miles away
What do you want to do
make a ball bounce off at the reversed value off of a player
but i can't even get it to moe
Start with the movement yeah
How should it move?
Is it one way or can it move up and down?
ok
You're not really at the point of needing to worry about that yet. Get it moving at ALL, then do collision reversal.
i got it to move and bounce off
just one question
how do they make it move the y axis once it hits a certain place
i wonder
or is it too difficult for me
What does that mean specifically?
you know the game ping pong?
Pong?
the ball does not go horizontally just like that
The issuie persists even after changing.. same line
Show the code (not what you showed before. The code causing the issue. OverheadDamage)
Vector3.Reflect is often used for bounces
well, yes, after you change the type, you're going to have to actually assign the reference
by default, the field will not contain anything
Or just use the built in physics and manually keep the velocity at a certain speed (magnitude)
how to use that when i am using transform.Translate
If you move via transform then you need to do manual collision checks
With CricleCast or something
nope I am hiding it from the inspector.. and i managed to change the color like that.. the text should be the same no? i didnt assign anything on the inspector for the color and worked.
Lots of pong tutorials out there, I suggest looking for one
I don't really understand what's going on here. Are you assigning meshProText when the OverHeadDamage component starts?
meshProColor will just be a color
and a color is a struct: it's just a value
if you do meshProColor = meshProText.color;, that just copies the current color into the variable
changing meshProColor will do nothing to the text color
if you need to change the text color, change the text color
Why do you have that as [HideInInspector]?
You really don't want that
You need to assign that field, and it'll be easy via the inspector
I have in my bullet class this changing color and works
oh ok.. wierd that even without assigning for the color worked.
you still haven't shown me OverHeadDamage's code
Color isn't a component
It's a value
I'm very confused.
got it . thank you
is there a way to give the argument to the OnClick() with the serialized field of the script on the same object?
yep:
public void OnButtonPress() {
OnSendInput(speedMultiplier);
}```
hook this up to the button ^
i meant on the editor level
sure:
public void OnButtonPress() {
levelManager.OnSendInput(speedMultiplier);
}```
im a bit confused where exactly should i put this code?
on the Play Button script I suppose.
ForceGroundDisconnect = Jumping | WallJumping | Dashing | Swimming}```
That last pattern only makes sense for enum flags, right?
Yes. Though with flags, the enum values that are not combined should have their values be powers of two
just out of curiosity, is there a way to do this witout flags?
I'm trying to make points on a map but my CollectPoints ain't collecting points and I'm not sure why.
namespace TowerDefense
{
public class Path : MonoBehaviour
{
[SerializeField] private List<Vector3> points = new List<Vector3>();
void Start()
{
CollectPoints();
}
private void CollectPoints()
{
points = new List<Vector3>();
Grids grid = FindObjectOfType<Grids>();
for (int i = 0; i < transform.childCount; i++)
{
GameObject child = transform.GetChild(i).gameObject;
Vector3 point = child.transform.position;
points.Add(point);
grid.Add(Grids.WorldToGrid(point), child);
child.SetActive(false);
}
}
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
to basically define (in the enum definition) that "these states are all in one category for comparison purposes"
If you want to be able to use bitwise operators to combine things, then each value must have a disjoint set of bits
or are flags just the way to go, here?
or else they'll overlap and it won't make any sense
note that System.Flags just indicates that you intend to use the enum that way
Wrong script entirely
you still need to assign numbers to each value
Grids is the one with the error - on line 31
oh ok.yeah assigning it now on spector worked. ty
Oh whoops
namespace TowerDefense
{
public class Grids : MonoBehaviour
{
private Dictionary<Vector3Int, GameObject> gameObjects = new Dictionary<Vector3Int, GameObject>();
public bool Add(Vector3Int tileCoordinates, GameObject newgameObjects)
{
if (gameObjects.ContainsKey(tileCoordinates)) return false;
gameObjects.Add(tileCoordinates, newgameObjects);
return true;
}
public void Remove(Vector3Int tileCoordinates)
{
if (!gameObjects.ContainsKey(tileCoordinates)) return;
Destroy(gameObjects[tileCoordinates]);
gameObjects.Remove(tileCoordinates);
}
public static Vector3Int WorldToGrid(Vector3 worldPosition)
{
Grid grid = FindObjectOfType<Grid>();
Vector3Int gridPosition = grid.WorldToCell(worldPosition);
return gridPosition;
}
public static Vector3 GridToWorld(Vector3Int gridPosition)
{
Grid grid = FindObjectOfType<Grid>();
Vector3 worldPosition = grid.GetCellCenterWorld(gridPosition);
return worldPosition;
}
}
}
float x = Random.Range(0, 2)== 0 ? -1 : 1;```
No. The number you'll get from combining the others will be pretty much random, as you do bitwise OR on them. It'll be the result of 2 | 3 | 4 | 5 | 7, which is 7, ie. the enum value Swimming
could someone explain what does the == 0 ? -1 : 1; part do?
and why do they declare the random range from 0 to 2
since max is exclusive
looks like you simply don't have a Grids object active in the scene
that means it wont return 2
sounds good. flags they will be, then
only 1 or 0 will be returned
it's saying if the random number was 0, use -1, else use 1
what if it is 2
OMG, I didn't put Grids..... it's called grids not grid
It is max exclusive it can't be 2
The float overload is max INclusive though
Random.Range(a, b) will return a number between a and b - 1
Wait never mind....
or sorry rather you don't have a Grid in the scene
very confusing naming you've got going on
also FindObjectOfType is really slow and using it constantly for things you're going to call a lot like GridToWorld is probably a bad idea
but you can optimize later I suppsoe
I do, it has the code onto it as well.
It will return [a, b) when a and b are int, [a, b] (both inclusive) when they are float
I figured that out. Would it be best to make a something to call back to?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hi, I'm trying to make it so if my pause menu is open, i cannot open the shop. and vise versa
then just check if the another panel is opened
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
And here I am again with reference problems hahaha. One day I will learn. So here is the code https://paste.ofcode.org/cqfCEJJ6PfC592mUctMfCG and the prob is for the boss works perfect. But for the enemy it doesnt. I am assigning on the inspector the enemy prefab. Surely that is not correct as it is not working, and findo bject I cant as there are too many on the screen. What would be a fix for that? The prob here is that the enemy is not taking the damage so he wont die
just grab the reference in OnTriggerEnter
that's the whole point of it
if (other.CompareTag("BossOne")){ < You now know that other is the Boss
thre's no reason to be using some externally defined reference
I don't get why I have to create the same structure within the initialization of that structure here
yeah people already tought me that here and I forgot.. omg true.. thank you !!
where is the "same structure" being created?
i have an issue where my particle system shoots "blood particles" to the side instead of straight upwards when my enemy gameObject is destroyed, and i have no clue how to fix this
worked., thank you next time I wont forget about that.. 😄
what is a simple definition of static and what are some examples of when you would make something static?
How unholy would you say this is?
var cr = Screen.currentResolution;
currentIndexRes = Array.FindIndex(resolutions, r => r.height == cr.height && r.width == cr.width);```
Probably as unholy as the fact that Resolution doesn't have a custom Equals method you can use...
ikr? thanks unity..
It could have been beautiful, just a single Array.IndexOf(resolutions, Screen.currentResolution), but no...
yeah one of those instances they just said "fkit gud enough as is"
oh yeah and I need 1 more refresh rate..
should I make a custom struct? so ugly
Array.FindIndex(resolutions, r => r.height == cr.height && r.width == cr.width && r.refreshRate == cr.refreshRate
Or an extension method
does this initialize my queue with 64 false values?
https://hatebin.com/tizwaqqbqf Hey. Its me again... My script works just fine with the pointer enter and exit. I also set the selected button in the start just so I can navigate with the arrow keys. What I cannnot achieve is that I could not figure out how to start the glow coroutine i have on the key navigation.
yeah, i'm just not sure if the queue will contain 64 null slots or 64 false slots like this
No, the queue will be empty. It's just that it's pre-allocating enough memory to fit 64 items, without resizing the array that it's using internally.
By default, capacity is at 8 when you don't specify that argument, and doubles each time you go past that limit
no, it sets the capacity of the queue; the number of initial elements. the elements themselves are empty . . .
Each resize, it has to create a new array and copy the items over, which is a potentially expensive operation
ok, so is there an easier way to tell it that I want it to assign them all as false without writing out 64 false things
For loop
create a loop . . .
ok, yeah I mean that's how I would've done it just looking to make sure there was no better one line practice, trying to get more proficient ya know
thanks
I can see my arrow keys navigate between the buttons inside the event system if that matters.
Well there's the overload that takes an IEnumerable<T>, but I got to check if it's intelligent enough to set an initial capacity to the item count in the enumerable
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah it takes the capacity of the enumerable so you should be able to do something like this as a nice shorthand
new Queue<bool>(Enumerable.Repeat(false, 64));
Google is your friend, but for unity a good example would be making some utility classes which you can freely access without a direct reference.
ex.
public static class VectorUtility
{
public static Vector3 CreateDirection(Vector3 startPoint, Vector3 endPoint)
{
Vector3 direction = endPoint- startPoint;
direction.Normalize();
return direction;
}
}
public class Character : MonoBehaviour
{
private void MoveCharacter(Vector3 startPoint, Vector3 endPoint)
{
//Calling this class directly by the name/type to access its methods because it's static
Vector3 direction = VectorUtility.CreateDirection(startPoint, endPoint);
}
}```
Help with OnTrigger method, not being able to make work for the minions
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
How can i get the timebetweenwaves to start once the last enemy has been killed?
Does anybody know how to make a ball movement system for VR so whenever you kick it it actually acts like a ball?
please do not crosspost everywhere..
stay in one channel
Soryy
Can someone help me out with this?
What do you mean by key navigation
Like using the arrow keys
Ah, ok so yeah IPointer is mouse specific
or pointer specific I guess since you can get it to work with some other devices
Yes. It works fine but I just cannot make my buttons have the glow effect when im navigating with the arrow keys. I tried OnSelected method but it does not work.
this script is attached to my text if that matters.
oh okay "static" makes a lot more sense now, thank you!
Usually UI components have a focus element method (or active element? I forget), and there's this:
https://docs.unity3d.com/2018.1/Documentation/ScriptReference/EventSystems.EventSystem-currentSelectedGameObject.html
im trying to make this gun sprite rotate to follow the cursor but it only flips on the x axis instead of rotating
I set the selected game object at the start in my code.
this is the code
it was working as normal until i started getting syntax errors and now its flipping on the x axis instead of following the cursor
Hmm I did not really get what focused does. What does paused mean?
Well, assuming you've multiple instances of this script, if you do this in start then it would be the last instantiated to be focused
And if you have multiples then you'd have a list that contains references to each of these buttons/text
so what your goal is to iterate over the list using the input
Does anybody know why this script is not working, I am kinda knew to this and came from UE5 wher blueprints dominate so Idk why this isnt working. Anyhow, I added this script to my player controller
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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 ```void StartDash()
{
Debug.Log("Dash started");
Vector3 mousePosition = Input.mousePosition;
Vector3 worldMousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector3 dashDirection = (worldMousePosition - transform.position).normalized;
playerRigidbody.AddForce(dashDirection * dashForce, ForceMode2D.Impulse);
Invoke("DeceleratePlayer", decelerationTime);
Debug.Log("Applying force");
Debug.Log(worldMousePosition);
}```
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
lol your meant to read the bot msg
attach a rigidbody to the gun and make it kinematic and freeze the rotation on the z
then replace tf.rotation = Quaternion.AngleAxis(angle, Vector3.up); with rb.rotation = angle;
hope this helps!
I did
I have just one script and this is it. I put this all on my text elements.
do you have any errors in console?
screenshot console window in playmode
Yeah, you need another script, some sort of manager that knows all these elements so you can add them into a container. Currently you've no way to navigate through all the buttons in a linear fashion. Pointer controls don't care about ordering because it's what ever you click on that's the next element.
but you didnt' send the complete code
No, the debug events trigger but nothing else
hmm could you screenshot your rigidbody component. the whole object inspector
oop
@rich adder
cannot implicitly convert float to quaternion
Show the code as it is now
The code given before (rb.rotation = angle;) would not work assuming angle is anything but a quaternion. It's a float probably
Hmm. I uhhh
I can see i navigate with the arrow keys in the event manager though. Is it not what you mean?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
When you press down on the arrow key, how does the program know what the next element is?
there is already some ordering on the scene, but you need to grab that information and put it into a script for you to use.
alr what about the rest of the object/where script is
it was working a while back but it was very impractical
I visualize the navigation and like I see them arrows going up and down. It is how its set on the buttons no?
i might just tear down the last 45 minutes and just redo the mouse movement script from the ground up
Ill send it (I dont have code for player decceleration yet though so thats empty)
You got a screenshot of the scene hierarchy?
no I mean you put this script on the object?
wanted to see the inspector
Ok
Yeah, so you can see that you do have some ordering, but you need some script that knows that ExitButton is element 0, Settings is element 1, ect. Just so you can apply the navigational logic.
Yeah, this was bad advice
#💻┃code-beginner message
Change it back. You could do rb.transform = //the rest of what you had
You need to build that quaternion somehow though.
this is not the one on the gameobject
Sorry but why do I want the navigational logic? To detect which button im on with the arrow keys?
So i can trigger the glow?
You need to know the ordering of the elements so when you press arrow key down it goes from element 0 to element 1
where is playerRigidbody field
you're missing that
can you screenshot your Debug print when you get them printed ? but screenshot the whole Consle window
But it already does that no? I press down arrow and im on the endless button
It says so at the bottom of event system
i opted to go back to an older version of my saved project which had the old movement system
Debug events Are in that screeenshot
only thing im wondering now
how do i import a variable from another script
i know you set the variable to public but what then
so hello i have a very annoying thing in my game im trying to make my character fall slower like a type of glide to float to a area but i still cant figure it out i tried a tutorial but that just screw me more basically just starting the game my
Ah, ok if the input system does it for you already (I'm used to doing most myself) then it's probably some eventsystem call back you're looking for. Let me see if I've used it.
send the whole script thru this https://hatebin.com
your linear drag is above 0 on rigidbody2D
that might be cause
Sorry for not telling that beforehand. I'm new to this whole thing i get confused easily.
Did you get the script? Also Ill check that.
Try that and IDeselect Handler
paste it on that site I sent you, save it and send link
I clicked save, now where is the link? Im supposed to send, the URL is no different
if you hit save the url changes
send url
hey guys I have a quick, somewhat obscure question that I hope someone would be able to answer. I'm currently making a keybind manager script for my game, HOWEVER! writing a reference for each individual key was kinda annoying, so I decided to write a script that takes a string I write beforehand and add it to the list of "key references" (which is a struct I made just to reference keys see which one is being pressed etc), and I noticed that the keycodes appear in Visual Studio with an integer beside them, implying to me atleast that there exists somewhere in the editor, an array with ALL of the keycodes (image included where I noticed this)
it really is fine if nobody knows because what I have now works fine, but is there a way to access keycodes using an integer for the keys index in this array? it would help me a lot. thanks for your time if you dont know anyways guys
public void OnSelect(BaseEventData eventData)
{
Debug.Log("Selected!");
if(glowCoroutine != null)
{
StopCoroutine(glowCoroutine);
}
glowCoroutine = StartCoroutine(ChangeGlowPowerOverTime(0f, transitionDuration));
}
I did this and its not working
I couldnt figure out the hatbin one but here it is on pastebin, https://pastebin.com/8uct8j5T
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.
Does the log get printed to console?
No
wait so this is a different script ?
does this one work? I assume it does since you got it from github
ok when i removed some recurring movement code my player hands stopped moving with my player body
The script is part of my player controller.
I sent the whole player controller
The keycodes are stored in an enum, that means you can use Enum.GetValues() to get their values, and convert the key codes to a number and back via cast operations
int key = (int)KeyCode.Space; // enum to number
KeyCode key1 = (KeyCode)420; // number to enum
yeah but this is the Tarodev controller
and they're moving the .velocity
so anything you do with AddForce is overwritten
Hello people of Unity, I am looking to learn C# and Unity but don't know where to start, does anyone have suggestions on where to go?
I see what you did there xD
should i use force or transform for jumping?
Force
transform gives no collisions
this doesnt make sense because my gun sprite is childed to my main player sprite
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Will it be pretty easy to fix that?
you would have to make Dash use .velocity instead of AddForce
which would require some Sort of IEnumerator(Coroutine) for a gradual decrease or use Update
so you can lerp the value
I made another script. Just to see if i get the log. It works this way.
Quick question gang if you load a scene async can you access gameobjects in that scene or no?
But I put it on the button not the text
I'm reading about the callback and people saying it doesn't work for some UI elements, ugh.
That is not really the only way. What referencing a value(variable) on another script really requires is getting a reference to the OBJECT (c# object, not necessarily unity GameObject) that HOLDS that value.
So, if you can, you can make a public field of the Type the other script is. Say it is MyScript
You would have
public MyScript script.
Not a public field for the value, but for the SCRIPT
Then you drag in the object with that script you want into the box in the inspector.
Then you can do
script.Value
You can't always just drag it in though, so I'd need to know more specifics.
Also see here for all the ways to set up references
https://unity.huh.how/programming/references
why I like doing stuff myself
event system good for dragging though since that is a headache to get working
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayButtonSelected : MonoBehaviour , ISelectHandler
{
public GameObject PlayButton;
public void OnSelect(BaseEventData eventData)
{
Debug.Log("Selected");
}
// Start is called before the first frame update
void Start()
{
EventSystem.current.SetSelectedGameObject(null);
EventSystem.current.SetSelectedGameObject(PlayButton);
}
// Update is called once per frame
void Update()
{
}
}
``` The script thats working on the button
depends how you look for them
thanks for the help! kinda works but it seems that unity expects people to have keyboards with over 150 numbers lmao 😭
Is too advanced for me if i try?
You can't reference Objects from one scene to another for example @open veldt
most of the search functions only search one scene/hierarchy
do i stick this snippet in the original script or the script where i want to import to
Ohh okay so I’d have to like do a singleton or something if I want something from another scene?
yup
👍 swag
Where you want to reference it from and use the value.
Import doesn't really make sense here, but I get what you intended
And that snippet will NOT WORK
It is just an example
Unless your script is actually called MyScript and the value is actually called Value?
No the numbers that appear just mean there isn't a KeyCode value associated with it
You should find whether they're valid for the enum (not sure how), and skip them as needed
oh damn guess I shouldn't be such a smart ass lol. thanks though this has saved me a lot of time!
Thanks for your time. Appreciate it.
The one I successfully get the log is on button
you know what, forget the update way
I hate it
If the button receives callbacks, then basically you just need to grab the text reference to apply the glow
One more thing, is this text directly on the button? If you were to IPointerEnter on the button would you want the text to glow.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlayButtonSelected : MonoBehaviour , ISelectHandler
{
public GameObject PlayButton;
public TextGlowOnHover textGlow;
public Coroutine textGlowCoroutine;
public void OnSelect(BaseEventData eventData)
{
Debug.Log("Selected");
if(textGlow.glowCoroutine != null)
{
StopCoroutine(textGlowCoroutine);
}
StartCoroutine(textGlow.ChangeGlowPowerOverTime(1, .5f));
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
I did this and it kind of works.
Yes only the text glows let me show you real quick
Ah, ok I see what you're doing. Yeah, what you got there is the idea if ISelectHandler is working.
can you not access any element from a queue?
They want to use events only which is fine
I have no idea why the text glows when i put it on button though 😄
I dragged the text in the inspector
I do not understand this question sorry
do you mean like arrays?
like is there no get() from a queue
or access by index
you can only peek() at the first element?
I set the play button to be selected in my code. The rest is handled by the input system i believe.
oh sorry I wasn't asnwering yuor question
Oh sorry my bad.
Thanks a lot for the help. I really appreciate it.
You can Dequeue() to get the first element off the queue. It's the design pattern of a queue, you can't, and shouldn't be knowing what's in the queue except for the first element.
It's like a real life queue at the supermarket for example. People arrive at the end of the queue, and people in front are processed first. First In, First Out (FIFO) collection type
You can maybe even move the IPointerHandler stuff up a level and just stick it on the button, but target the text reference
but if it works then it's all good
ah intersting, so is the memory storage for each element of the queue like scattered and the system has no way of knowing what is where?
I haven't learned about data structures before
No it's stored contiguously in an array in the back
It's just that it doesn't allow you to look anywhere you want
why not?
It's the design pattern of the Queue
optimization
I believe im not qualified enough to understand what you mean by that. I never tried to use my head this much before. I will take a look tomorrow. Thanks again!
If you need to look at any element, then use a simple List or array, queues are not made for such manipulations
https://hastebin.com/share/ufusinenis.csharp this is my storm circle code and it is not shrinking in game
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I'm trying to keep track of events that have happened over the past second, so I figured a queue is best for that right?
it's continuously updated
Yes sure, that's one of the use cases
Dequeue one (or more) elements each frame if there are any in the queue
And process them
is there anyway of making my character move just the x axis instead of turning the y axis into 0?
BeeRB.velocity = Vector2.right * speed * horizontal;
}
make a new vector2 with only x changing
BeeRB.velocity = new Vector2(1 * speed * horizontal, BeeRB.velocity.y);
BeeRB.velocity = new Vector2(horizontal * speed , BeeRB.velocity.y);
like thatt=
oh i got it xd
i dont think i even need the 1 right
because horizontal gives a value of 1 through -1
thanks you
Multiplying anything by 1 does not change its value, so yep it's not necessary to have it here
May I get a hand with this please
Get rid of while true first of all. If you are actually calling it more than once, you don't want it looping forever
makes sense
You have a check for when all enemies are killed, so that should be about the only change you need. It will call when they die, then wait for the time, then spawn them
{
GameObject.Destroy(waypointsAdded[waypointsAdded.Count - 1]);
waypointsAdded.RemoveAt(waypointsAdded.Count - 1);
}```
destroyed gameobject still exists for some time, right?
Till the end of the same frame it is called
also note that the c# object will continue to exist
so even if the unity object was instantly destroyed, it wouldn't matter at all
the c# object isn't actually becoming null
that's just a trick that anything deriving from Unity.Object pulls
yeah Unity overrides != and == for Unity.Object
Can someone plz explain to me why I’m passing through objects even though I have colliders on each object
show collider
also how do you move (code)
public void MovementPlayer()
{
// this block of code gets the left, right, up, down movement
horizontal = Input.GetAxisRaw("Horizontal");
vertical = Input.GetAxisRaw("Vertical");
if (Input.GetKey(KeyCode.LeftShift))
{
rb2D.velocity = new Vector2(horizontal * playerSprintSpeed, vertical * playerSprintSpeed);
}
else
{
rb2D.velocity = new Vector2(horizontal * playerMoveSpeed, vertical * playerMoveSpeed);
}
}
my colliders are all circle 2d
exept for the capsule
nothing was changed on them
lemme see gizmos
pardon
ok
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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.
heyy, does anyone know wich is the best way to develop a game in realtime with two people?
my bad it took me a while
git is the closest to "realmtime" you get
to use github desktop you mean, right?
thats one client sure
But, we both can not be editing the same thing at the same time, right? cause that will make overwriting problems, no?
yup
and you recommend me github or another git service?
github is pretty good
And for example, if my game has a garden and a house, one person can edit the garden and the other the house at the same time, but until one of both people stop editing the house or the garden the oder must not edite the same thing, i'm right?
split them up into different scenes so you can work on both at same time
so, have the house in one scene and the garden on another, right?
but what if the house is over the garden on the playmode view?
how could i do that?
what's the proper pattern to pingpong a list?All_Ally[(int)Mathf.PingPong(TurnCount, All_Ally.Count - 1)];
nvm that's working already
something else was the problem
hello everybody can somebody borrow me their super genious head
so i had this problem for a bit i kinda figured it out but now i added a new mechanic and now it kinda broke my mechanic
if(Input.GetKey(KeyCode.Space) && BeeRB.velocity.y <= 0)
{
BeeRB.gravityScale = 0.5f;
}
else
{
BeeRB.gravityScale = startGravity;
}
//Fall Faster
if(BeeRB.velocity.y <= 0)
{
BeeRB.gravityScale = fallGravity;
}
else
{
BeeRB.gravityScale = startGravity;
}
so i had these two one was for gliding and the other one was for falling faster
if 2 methods depends on one will just one execute?
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 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 runs top to bottom, one line at a time.
Whichever one sets gravity scale last wins
wait so you are telling me they cannot change the same value but it is in the update method
I'm saying they both change the value
And whichever one changes it last is the one that "wins"
Because that's what the gravity scale is at the end of the function
oh ok so what could be a solution for this?
how would i do unzipping files
Think through your logic. When do you want gravity scale to be 0.5, when do you ant it to be startGravity, and when do you want it to be fallGravity
Thought you were talking about levels . It depends what exactly you mean work at the same time
i can just put them together in the same if let me try that because they both use the first condition
i will try and see
omg its works @polar acorn thanks a lot
Hey guys. Im making this silly golf game, and was wondering if anyone knew how I can achieve the effect in the video of Camera parent and ball child rotation, without actually having the ball the child of the camera? I've tried applying the same rotation to the golf ball but it doesn't have the exact same effect.
for the camera I'm simply adding a y value to the eulerAngles
i need to access Application.dataPath but access denied how do i give it path permissions
why would one use an enum when they could use an integer?
beacuse enum values have names
which is more grokkable?
mode = 3;
mode = GameMode.Deathmatch;
You can also enumerate all valid values for an enum type
with System.Enum.GetValues
the compiler can also check that you've handled every valid enum value in a switch expression and warn you if you missed one
oh so they are more flexible and better understandable then right?
titleText.text = mode switch {
GameMode.Deathmatch => "Deathmatch",
GameMode.CTF => "Capture the Flag",
};
if I added GameMode.TeamDeathmatch to the enum, I'd get a compiler warning
Okay, thank you so much! The examples made me understand a lot better to :)
no prob (:
So RaycastHit2D.point can be used with raycasts, and I remember seeing you can also use Raycasthit2D.point[0]. Does that return the colldier you hit first?
Or is there no difference?
Point is a Vector 2 not an array of objects
Using the indexer operator ([]) well yield you the x or y component of the Vector 2
Ya mean this method:
https://docs.unity3d.com/ScriptReference/Physics2D.RaycastAll.html
How does this even work in 2D
What doesn't work?
Ah, I guess if you have colliders overlapping it makes sense
Yeah, im just thinking how you don't really have depth, but stuff that overlaps would be the usage
you do know that you can use a direction other than Vector3.forward for a 2d raycast, right?
Oh, true
For the RaycastAll? You'd get back an array of hits which you can then access to get a point in space for each.
People say it's not always ordered from which is hit first, but you can iterate over the array then order it yourself too.
Normal raycast you get back a single hit (whatever is hit first that meets the requirements) and what you can access from that hit is listed here:
https://docs.unity3d.com/ScriptReference/RaycastHit2D.html
Point would give you the vector2
How do I write a script for movement in fps I wanna use it for a bird
hello quick question my character move with velocity but in the end of my movement my character kinda drags a little bit
hatebin.com/fuqfvwpwdv
i can just put the velocity to zero after the movement but i want it to decreased not completely stop so i doesnt look so robotic
what do you mean by "drags a little bit"?
also you need to share more of the code than that
I googled it and I am not able to understand the code given there, there is no explanation how it works
like after the velocity it still retains some velocity after that so it start moving by itself slowly
you're probably using GetAxis instead of GetAxisRaw
called it
wait so i need to just changed getrawaxis?
You can post what you tried and we can help explain
what is the differenced?
Smoothing vs no smoothing
GetAxis includes input smoothing which means your input will reduce to 0 over time after releasing the key(s)
GetAxisRaw is ONLY -1, 0, or 1
of course you are also not setting velocity to 0 when there's no input anyway so it will retain it's velocity until its physics has made it stop or you start using some other input because you only apply your input when it is not 0
well now it moves way faster and cooler but it still slides after the input
that is the thing i want to not make it stop completely but slowly slowly
then go back to GetAxis and remove the check for whether the input is 0
I am on my phone so can I ask in a later time
or add more drag to your rigidbody
If you're using rigid body physics, you'll have to introduce other forces to slow/stop your moving object
well yeah the thing im trying to do, is putting some force over time
to neglect the amount generated after he stops
oh wait a moment i can just divide them because the action is on update so is gonna do that constatly
i'm guessing you missed the suggestion of adding drag to your rigidbody
linear
the second if statement never returns true, could someone explain why, i've tried to use context.duration before and never got it to work.
also I just realized invoke isn't doing what I want there but regardless I can't get the duration check to work
(the rest of the function works)
That looks like the function may be part of the "new" input system, how are you calling that function?
Ah, I havnt used that component to handle input, though likely what may be happening is that your function is only being called once when the input changes (for example, the first frame the key changed from not being pressed to now being pressed down) - you can confirm this by adding a Debug.Log to the start of that function, I believe there is a setting in the action map for the bind to allow it to continue receiving input, or possibly on the input controller itself, otherwise another solution would be to poll the input yourself in Update
ok thanks
You were right about part of it, I got the duration check to work, but now the original press wont work. I added a hold interaction the the action (NEVERMIND THIS, I found a weird solution by just saying when context.duration == 0 do something, instead of context.performed.)
i have no idea how to make an strom circle that works because the 2017 tutorial one is broken and the 2d one i am following is from 4 years ago
{
public Transform turret;
public Transform turretBarrel;
public Transform target;
// Update is called once per frame
void Update()
{
turret.LookAt(target);
turretBarrel.LookAt(target);
}
}
``` im trying to aim gun turrets at a target, but with the actual turrets they need to only rotate along the y axis while the rest stay null, but with this skript they rotate along the x axis as well, how would i get it to only rotate along the y axis for the turret and the x axis for the turret barrels?
So, we were talking yesterday (day before? Time is crazy for me lately), but I don't think I got an answer. What was wrong with the code you have? It is up to date, and I didn't see anything that wouldn't work
You could use the LookAt overload that takes a vector. Then create a vector with the turrets own y position and the targets x/z position
Same but only the targets y position for the barrel
Wait... i don't think that would work for the barrel...
i have a simple question but i've been working at it for a while now 4 some reason my unity just decides not to let me debug and i have no idea what the issue is
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
void Start()
{
Debug.Log("hi?");
}
}
Yeah, but trying to look at its own x and z would cause issue
I think the barrel would be fine as you had it
yes
show the console
done
have you dragged the script to the gameobject?
{
public Transform turret;
public Transform turretBarrel;
public Transform target;
// Update is called once per frame
void Update()
{
turret.LookAt(new Vector3(turret.transform.position.x, target.transform.position.y, turret.transform.position.z));
turretBarrel.LookAt(target};
}``` the turrets are now on their sides

Sorry 🤦♂️
Reverse it. Target x/z Turret Y
alrrr
it says sytem.obsolete and the i get errors like cannot apply [] to an ine expression
Says it on what?
And I don't understand the second part.
Wait... you have two Updates...
Maybe that is why?
I'm gonna just put the code in my IDE and see what is up a little better
i hit enable to resolve an error i thought when i was saving it
what does Transform.TransformDirection method do ?
did you look at the docs? https://docs.unity3d.com/ScriptReference/Transform.TransformDirection.html
which part is confusing for you specifically
i am new to unity so i didnt know how to use docs
i dont understand what it returns
It returns a Vector3 that represents a direction in world space
google will lead you to the docs, you dont need to do anything in unity.
you give the method a direction in local space and it gives you that vector3 as world space. Local space means the position relative to another object, world space means its true location in the unity scene
thanks
thanks mate
public Vector3 TransformDirection(Vector3 direction);
[access modifier] <return type> <method name>
If I have two vector3s and I want to move one so that the distance between them is N but I want to keep the angle between them the same, what's the best way to figure that?
Wait, is this the current code?
As soon as I copied it into my IDE, a bunch of simple syntax errors popped up. Like missing parentheses, variables, a line of code is after a return.
Calling count on an int
Is this copied or did you modify it?
#💻┃code-beginner message
Yeah, 15 errors in that one script
modifyed from an yt video
angle relative to what? There is no rotation if we are just talking purely about vector3 since this is just a point
There are methods inside of methods. It's..... reaaally rough. It needs a LOT of work
Can you send the YT video
local methods, FTW!
The locals are a second Start and a second Update, inside of a Start, haha
damn, way to mix it up . . .
ok here it is https://youtu.be/JuqRnsUUcho?si=b7PKrMzzoVjtvDml but he update his C# as well on video number #12
Unity 2017 - Battle Royale Series - Part 7 - Shrinking Circle!!
(Full Tutorial + Free Asset Download!)
Download the assets used in this episode here:
www.polygonpilgrimage.com/Downloads/ShrinkingCircle.zip
Thanks for watching!
Please Like and Share!
- My Twitter - http://www.twitter.com/PolygonPilgrim
- My Site - http://www.polygonpilgrimage...
i wanna learn fps movement where should i learn ( i tried youtube and i cant understand anything )
Yeah, I tried to go to his repo, but it doesn't even show those scripts. There was a download for a ChangeCircle script and it's just... significantly different than yours.
You've added and changed so much I'm not sure how to get back from there. There are so many fundamental errors and issues that I don't understand the reasoning behind. I'm not sure how I or anyone else can really help with that.
As hard as this is to say, and certainly to hear, I feel like... starting over may be a good idea.
Someone else may be able to help 🤷♂️ but there is a lot to unmodify.
For anyone else:
StormController:
https://hastebin.com/share/ufusinenis.csharp
WorldCircle:
https://hastebin.com/share/kavojolohu.csharp
he inclues the updated c# in the decpriton of the one
Yeah, I got that one too. It's just... SO different from your code.
There are so many things that just cannot be done in C# in yours. Like:
void Start()
{
void Start()
{ }
void Update()
{ }
} // Start and Update should not be in ANY method.
CloseTimes[closeTimeIndex] // this value is an int, not an array (or list)
if ((int)TimeElasped > CloseTimescloseTimeIndex //missing a parentheses, missing the square brackets, and again, is an int not an array
StormCircle((float)(XRadius * (ShrinkRadiusFator * 0.01)))[1]; // this is a type, not a method, right?
NextCircleTime(); // this method doesn't exist
TimeElasped[closeTimeIndex] // this is a float, not an array
CloseTimes.count // int, not array
return -1;
CloseTimes[++closeTimeIndex]; // innaccesible because it's after a return
It's just... like nearly everything is not right
What have you looked at? Have you gone through Unity's pathways?
i saw some youtube videos but i didnt look at the pathways
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I really recommend starting there instead of with youtube.
I also recommend taking a c# course:
https://www.w3schools.com/cs/index.php
i know a few languages so i am familiar with the syntax but i wanna know about the methods and functions in unity
When you say "a few languages" does that include c#?
If not, it wouldn't hurt to do the w3schools course. It's short
But up to you, you can just skip that and go to the pathways if you feel comfortable enough
i know c and c# is very similar so i think its fine , is it ?
Uhhh, kinda...
There are some SIGNIFICANT differences
Even if You know c# doesn’t mean that you know the method in unity
any tutorial on how to animate two seperate game objects to do something together?
for example, you do a special attack on an enemy that involves throwing an enemy?
Hi everyone, just new here but already working on Unity for a long time I'm studying DOTS and for some reason my camera is rendering weirdly.
The blurry ones are my gameobjects that have a DOTS authoring component and the cannon doesn't have any script attached to it and it looks normal. Here's a preview of what's happening.
Here's how they should look like in a different angle.
I'm using URP and Entities.Graphics, maybe they are conflicting
Hello, i was converting a movement script with the built-in character controller from this https://docs.unity3d.com/ScriptReference/CharacterController.Move.html , to a state machine from here https://www.youtube.com/watch?v=qsIiFsddGV4 . There are 2 things that i want to ask
- When it transitions to the jump state, it immediately go back to idle state, does anyone know where the problem is and how to fix it? i think there is a split second it is still grounded so it goes back to idle state but i don't know how to fix it without changing the abstract class
- There is a delay when i want to jump using the state machine version compared to the non-state machine version where it is all smooth, does anyone know what is happening?
the code is here https://gdl.space/desotukixa.m
thank you 🙏
- Give a moment of time that prevents you from transitioning to ground state. I can't really of other ways regarding that. That's how I dealt with it too.
- Can you describe it more specifically?
Is there a trick for deactivating objects for the pool system? Currently when my 1st spawn iteration finishes from the pool list, it refuses to start from the beginning and re-iterate.
{
if (pool.Count == 0)
{
Debug.Log("Pool is empty, creating a new object.");
CreatePooledObject(); // Optionally increase the pool size
}
var obj = pool.Dequeue();
ResetObjectState(obj);
obj.SetActive(true);
Debug.Log("Object taken from pool and activated: " + obj.name);
return obj;
}
public void ReturnObjectToPool(GameObject obj)
{
ResetObjectState(obj);
obj.SetActive(false);
pool.Enqueue(obj);
Debug.Log("Object returned to pool and deactivated: " + obj.name);
}
private void ResetObjectState(GameObject obj)
{
// Reset object state as needed
obj.transform.position = Vector3.zero;
obj.transform.rotation = Quaternion.identity;
var rb = obj.GetComponent<Rigidbody>();
if (rb != null)
{
rb.velocity = Vector3.zero;
rb.angularVelocity = Vector3.zero;
}
// Reset any additional components or states here
Debug.Log("Object state reset: " + obj.name);
}```
Also, using enum is a bit strange here, I'd get a reference to the StateMachine for each State and pass this when switching state.
That should eliminate some switch case. If you used one.
- alright, thank you 👍
- with the state machine there is about a half second delay between pressing space and the character jumping. with the normal class there isn't. i don't know what is causing it
huh? i didn't touch unity for a week... not sure what happened here
Not much, just clear it
hopefully nothing happened to my project
Nah, its quite common to have 1 error like that sometimes, no idea where it comes from. If it doesn't come back it's fine.
Isn't it Release instead of Enqueue? https://docs.unity3d.com/ScriptReference/Pool.ObjectPool_1.Release.html
Where did you read Enqueue?
Holy crap
