#💻┃code-beginner
1 messages · Page 380 of 1
is it alright if i dm you? i'm still kinda lost but dont want to flood the chat.
make a thread!
I use prefabs because that lets me consistently style all of my UI elements.
Which is why you should probably instantiate prefabs
i cant in this situation
Is there a way around it?
Then that would mean that you'd be facing diagnoally
around what
I cant put it in here
A transform is not a vector. We've been through this
You can't set a transform to a vector
because they are not the same things
why can't I assign a Banana into an Apple variable?
They both have positions
both are edible
If someone asked for a picture of my cat and I sent them a jpg of a coconut that would not be what they requested
Exactly
it wouldn't even do anything useful
Vectors are positions
you'd be just...replacing your Transform reference
Transform has a property .position. Vectors do not
Mby
with a new, bogus reference to the wrong type entirely
also, this screenshot doesn't demonstrate an actual problem
were you trying to do something like this?
More like, "Why can't I eat this tree?"
public Vector3 spawn = new Vector3(0, PlayPos.y, 0);
"Bananas come from trees so why can't I eat the tree?"
Why cant i put an float in there tho
in where?
In the X axis
Does your camera rotate with your player?
I genuinely don't know what you're talking about. This shows you constructing a new Vector3 with an integer
You can, just not outside a method. You can't put Speed in there because Speed doesn't actually exist yet. All of those variables get created at the same time
Did you try to do new Vector3(1.5, 0, 0); ?
In Start for example, you could change spawn to a value including Speed
But i want the cube to spawn at (PlayPos + 10, 0, 0)
But that isnt possible so i need to use NEw vector
While playing, click the player again and see what direction the blue arrow is pointing. That is the direction your player will move when you press W.
Yes, you aren't allowed to use a field in a field initializer.
So do that
Just calculate it in Start.
So if you want to change where the cube spawns, why are you looking at this script?
Look at where you're spawning it instead
"cannot convert double to float" 😏
it works but it's like some directions are swapped?
This is the spawn script but i only got the where from the player it should spawn not the acctual spawning
I bet the arrow points in its "right" direction, then
You can fix this by adding a 90 degree rotation
Can you show the updated code?
was working with some opengl library earlier and it was expecting me to label all integers and zeroes as float despite it only using float anyway
thanks that was a dumb mistake my bad
Quaternion.AngleAxis(90, Vector3.forward) * someOtherRotation
This script doesn't spawn anything
Can you show the inspector for this object?
Yes. Not yet i only focuse on where it should spawn not the spawning
Then what's the issue?
When spawning get the player position and add your offset
But i want the x to be set to an float -10
If your issue is you want to spawn something at a specific spot, but you aren't spawning that thing at all yet, then what's the issue? Solve the problem when you are actually using it
Then do so
There does not seem to be any scripts in this screenshot
then...add two vectors together
add spawn to another vector
or just set the x component of spawn before you use it
Okay, so your speed is positive, meaning W should be moving you in the direction of this blue arrow. That is, away from the back wall. Is that not what's happening? Note that your camera does not appear to be facing in this direction, so you'd be moving to the side of your camera from the looks of it
interpolation can smooth out rigidbody movement
The code you shared would move this object in the direction of the blue arrow whenever you press W. If that is not what you are seeing then there is something else affecting it.
Now that it works. How can i set the PlayPos to the position of the player?!
you guys are still here? Impressive 😄
PlayPos is not a position, it's a transform
Drag in the object you want PlayerPos to refer to
Ye but then i cant set it in the X on the "Transform.poistion"
why not
Because i thougth i coulndt mix Vector and transform
You can't
Yes?
transform.position is a vector
Transform is not a vector
It has a vector property named transform
See, red?
This would rotate the object, but your movement would still be in the direction of the blue arrow
A Transform is not a float either
So how can i set The X axis to the player's x axis ?
Get the player's X axis
Instead of the whole ass transform
I don't know what else is in your project. If the code you've shown is what you're running, then pressing W will move whatever object gracz is in the direction of this object's blue arrow
If that isn't happening, something else is moving it in a different direction
And nothing you've posted would do that either
You still have this weird -90 degree angle offset in your camera script
I do only the x but how?
Camera is child of gracz (which is the player?) and has its own local rotation
Imagine this:
There are two people, Billy and Jimmy, standing in a field. You tell Billy he needs to move to the left. Billy asks "How many steps to the left should I take?" and you respond "Jimmy". Does that make sense?
So the camera's rotation will be player rotation PLUS camera rotation, right
Doesn't sound right
I think billy is dyslektic
or smlt
Is the camera selected in this video?
But how can i do it with an variable?
Can someone help me figure out why is this not working? the player will not get deleted when it enters the box
Or is that even possible
You have the transform of the object you want to know the X position of, correct?
yes
This is a 3D collider
Is there some reason you expect the player to get deleted when entering this box?
So, get the X value of the Position property of that transform
What if you remove this line: MouseX = -90f; from the camera script?
Instead of all this 20 questions. Why don't you go and look at the Transform documentation?
What if you change graczcam.localRotation = to gracszcam.rotation =
oops, switched it to a 2D one but its still not working
Thanks @polar acorn (:
when i click start in unity editor and hold lctrl and click outside of the game view unity keeps the value from when i pressed it and makes it the unpressed value should i worry about that?
it has a player tag? isn't that how it supposed to work
You would need a script or something
the one on the left
it doesn't happen magically
Is it still a trigger?
ah but:
#💻┃code-beginner message
There's code in the far left of the screenshot, tap to open the full size, it's cropped on mobile
yes
Time for Debug.Log
Both at the same Z position?
Post both full scripts in a paste site !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.
yep, I also added a debug log, but it never gets called
Are you moving the player via rigidbody, and not through translate?
Oh wait hang on
So it's a trigger but youre using OnCollisionEnter2D? Or did I miss something
I've missed a very obvious problem
and it's this
You even asked if it's a trigger 😄
Which made me notice
Your z and x are flipped
In ruch script
ruch
how i treat struct as string for its default value
huh
i know i can alter what it prints by overriding tostring
you mean like an implicit cast?
fixed it. Thank you guys
Example with code, please!
i would just use ToString().IndexOf()
don’t overcomplicate your struct with shit it doesn’t need
holder.IndexOf("test");```
like this
i want get while not holding custom variable
it holds many more values
This would be a compile error
So, an implicit conversion from string to custom?
unless custom is a subclass of string I guess?
you need to write a custom comparer for your List
yes i want it to be treated as string by default but also store variables inside itself
i would recommend you not implicitly cast with string unless you have a really good reason to
because this isn’t going to work the way you think it will
You can't. That's not how C# works. A type cannot morph into another one at will
What are you trying to solve here
Talk about your issue, not how you're trying to solve it
maybe someday anuked will not try to use strings for literally everything. but it does not seem like that day is today
getting custom variable without custom variable in hand
using strings for that is bad juju
it will fuck you up. your teeth will rot, and your hair will fall out.
and the compiler will yell at you
since it feels worse to create new struct out of string just to compare it in list
you have a deeper problem here, tbh
Just use a List<string>? I don't get the issue (is there even an issue to begin with?)
im rewriting it for the third time since when i did one thing it didnt matched the other
so im looking for universal storage
that is not how this is going to go down
trying to get variables by strings is really bad
since that var stores more stuff inside
you should be using objects with specific references to other objects
the closest you might need is a singleton, where you can get a reference to the unique instance of a given class
but at this stage, i fear your inexperience will cause you to spam singletons unnecessarily
what you are trying to do is quite possible. However it would take a great deal of work and a lot of in depth C# knowledge to make it
literally not a single word of what you've said has made any sense whatsoever
You're just kind of vomiting random keywords
you can do it. But you really should not.
My brain is having a real hard time understanding that, does anyone have a transpiler??
class part of storing any amount of variables in it and interface part of treating object itself as another var as well
he wants like a dictionary, where string goes in, and out comes a variable tied to that string
Okay, that makes sense. I have no idea what the hell "looking for a mix of class and interface" has that relates to that though
he’s trying to code with references by strings. you’d only do this if you are so inexperienced that you haven’t had that bite you in the ass yet
so it is understandable in a sense.
Types, not vars.
List<Thing> someRandomName = new() /*
TYPE | VARIABLE
Make sure you use the correct terms because that's just confusing us
though i can just use tostring.indexof fine
Can you like, put a bit of effort into writing sentences that make sense
It's not going to work. Doing .ToString() on a List<Thing> is going to give you the string "List'1[Thing]" literally, and using IndexOf() on that is pretty much nonsense
He is most definitely just trolling
me no agree. me like am help interfaces?
You could just use Linq FindIndex
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findindex?view=net-8.0
a yeah i probably wanted to use that
just forgot the function as i was using dictionaries so much
Something like holder.FindIndex(item => item.someString == "test")
for (int i = 0; i < 15; i++)
{
StartCoroutine(WaitForSeconds(1.5f));
Instantiate(enemy1Prefab, new Vector2(9.5f, Random.Range(-2.5f, 2.5f)), Quaternion.identity);
}
IEnumerator WaitForSeconds(float secondsToWait)
{
yield return new WaitForSeconds(secondsToWait);
}
``` is there anything wrong with this code? because its not working for me. its supposed to spawn an enemy every 1.5 seconds, but instead it just spawns them ALL at once
You need to spawn them in the coroutine
i must pray for him. his inability to write basic english gives me no confidence that his spelling will be what a string=>ref system demands.
oh okay ill try that
So the question was just "How can I find the index of an element in a list using one of its variables?" lmfao
that but adding variables that i cannot create
so i wanted use string to find a struct
{
for (int i = 0; i < 15; i++)
{
StartCoroutine(Wave1());
}
}
IEnumerator Wave1()
{
Instantiate(enemy1Prefab, new Vector2(9.5f, Random.Range(-2.5f, 2.5f)), Quaternion.identity);
yield return new WaitForSeconds(1.5f);
}```like this?
or more like getting as finding is bad idea considering im running loop inside a loop already
No. It’s how do I string the list of index with the variables so I can access the string but not the list and I can get an object?
With a mix of class and interface
No that will start all 15 at once and then after 1.5 seconds will spawn them all
Move the loop inside too
Interface classes with index and list, but with indexof string and Turing Completeness.
private void Start()
{
StartCoroutine(Wave1());
}
IEnumerator Wave1()
{
for (int i = 0; i < 15; i++)
{
Instantiate(enemy1Prefab, new Vector2(9.5f, Random.Range(-2.5f, 2.5f)), Quaternion.identity);
yield return new WaitForSeconds(1.5f);
}
}
``` okay i changed it to this and it worked. thank you!
ok i’m done. even if it was warranted
ok about this one i can go more detailed
i have a struct, each struct holds reference to array of all other structs, struct also holds block of data which can be got as string, and this string holds array of strings from different structs of same type which already exist in array
and question was how to get these sub structs using a string, but if there aint good way i will just do a loop comparing strings each time i need them or something
Hey, I'm trying to do a simple raycast:
var hit = Physics2D.Raycast(transform.position, attackDir, 100f, _targettingLayer);
And I have this debug:
Debug.Log($"00000 {hit.point} == {hit.collider.transform.position}");
Which gives me this:
00000 (-4.00, 0.00) == (1.00, 3.37, 0.00)
However the 2 points are quite far away (first element is green circle and 2nd red circle) and I can't figure out why? (The green point should be ignored by the layer)
I'm on Unity 6000.0.5f1
_targettingLayer is a layer mask, right? Not a single layer index
Also show how you calculate attackDir
whats a good c# IDE u can recommend to a beginner?
Yup
_targettingLayer = 1 << LayerMask.NameToLayer("Wall");
_targettingLayer |= 1 << LayerMask.NameToLayer("Enemy");
var attackDir = closest.transform.position - transform.position;
This is wrong
ah
Well
Actually it's ok but unnecessarily complicated
Use LayerMask.GetMask("Wall", "Enemy")
looks like my code :)
Sorry I jumped because I saw nametolayer
Create a public LayerMask field, and Unity will make a nice dropdown in the Inspector, as an alternative
Rider
I usually have my own layer utility class that'll give layers/masks an enum type
My code is a bit cleaner now but I still have the same issue
if ur looking for free its Visual Studio Community
I mean if your Collider is offset from the sprite this can happen
One thing to check first is to make sure you're hitting the object you expect
Print the name
ah wait yeah, it collides with trigger colliders too right?
yes,
no need to spend time guessing.. full debugs loggin the collision, the collider, name, the time or w/e is the best start
by default i believe they ignore trigger colliders
🤔
what do you think of vscode?
Yes
i use both
Print the object name
VStudio community is easier to use for a beginner
but im starting to like VSCode better
whjy?
i personally like the UI better
vscode so clean
and ive grown pretty dependent on abunch of extensions i use
i mistaken, raycast do detect trigger colliders.. (in my 3d scene atleast) im guessing 2d similar
thought u needed to apply a contactfilter but not the case
That explains things a lot, thanks to both of you for your help!
yea, debug the name of the collisions 👍 it'd be helpful most times
vscode is a bit more complicated to configure but not too bad, its better now b/c Unity's editor plug-in just works much better
and for some reason, i've always had issues w/ Visual Studio Community.. anytime i would rename a file, or move a file from one folder to another.. it'd force open VS and cause editor to have to recompile
even if i didn't want to open the script yet
how do i not show decimal numbers again?
i know i need to do smth like ("F1")
but idk how i forgot
If I want to make a singleton of a player class but have 2 seperate scripts for Player and PlayerMovement how should I approach which script has the singleton?
someFloat.ToString("F0")
oh thank tyou so much
Or just cast to int
mah its fine
PlayerManager.Instance.Players[0]
Also GameManager.Instance.Players[0]
if one references the other u can just use a singleton on the main gameobject, thats how i do
if there is only one player, then the player can be the singleton that references the player movement object
player.Instance;
player.Instance.PlayerMovement```
oh, if it's a single player then playermovement should just be referenced by player ;p
is how i feel too
aight thanks, guess ill start with visual studio first =)
ya, if you wnat to swap over later its not that hard
may be beneficial to learn IDE's in general using VS Comm tho
its more user-friendly
private int OmrilolPrice = 25;
public void BuyOmrilol()
{
if (Money >= OmrilolPrice)
{
Omrilol++;
MoneyPerSecond += 1;
Money -= OmrilolPrice;
OmrilolPrice = Mathf.RoundToInt(OmrilolPrice * 1.35f);
OmrilolPriceTXT.SetText("Omrilol Price: " + OmrilolPrice);
OmrilolCounter.SetText("Omrilol: " + Omrilol);
}
}```
any idea why this code isnt rlly working?
i got the money to 10 i click it ajnd nothing happends
What calls BuyOmrilol
oh nvm i found out why it stopped working
I've created a separate scene for my Audio Settings with sliders etc.
But now the volume won't change to the correct/saved volume until I go to the Audio Settings scene.
Any way to call for the values from the Main Menu?
u can additive *** load the scene.. so they're basically stacked and should be able to reference/control it
Is there a way to set anim.SetTrigger("die") to false?
reset the trigger
MainMenu scene loads in.. and sticks around thru the entire game
this is additive loading btw
is that not what i said? lol thats what i Meant
thanks for the eyes 👍
ofc. im still undecided what the best way to do it is.. since its a small game.. ive debated on using a gameobject for the main menu
but soo far the additive scenes work pretty solid.. and help act as an extra layer of organization
their issue can be solved by just loading and applying the saved settings when the game loads instead of only loading when their settings scene loads
true true.. I have temp values.. for when im at teh menu...
when i change the slider i update these values immediately.. (to show the sliders to be accurate)
and then if the user saves.. they get set in the main data.. and modify the audio manager/mixers
if u cancel then the temp values get purged and the sliders all get reset to their default
but.. its probably my most complicated system that I've hand-written.. sooo its quite hidious 🤣
So I've got this now:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class NewBehaviourScript : MonoBehaviour
{
void Start()
{
StartCoroutine(LoadYourAsyncScene());
}
IEnumerator LoadYourAsyncScene()
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync("AudioSettings");
while (!asyncLoad.isDone)
{
yield return null;
}
}
}
It works, like it loads the audio settings, but it also changes the scene to the Audio Settings scene..
quick question do you find this terrifying?
And there is a small delay where the sound is a max before it changes it
Look at the docs for load scene async. There is a 2nd parameter u can add to load additively
this is a code channel
Not a code question
this also seems pretty unnecessary. just load the stored settings when you launch the game, you don't need to keep the entire settings scene alive for the entire game
That's what I want, but I'm unsure how to load the settings
As they are stored in another script / scene
well how have you saved the settings
public class VolumeSettings : MonoBehaviour
{
[SerializeField] private AudioMixer myMixer;
[SerializeField] private Slider masterSlider;
[SerializeField] private Slider musicSlider;
[SerializeField] private Slider SFXSlider;
private void Start()
{
if (PlayerPrefs.HasKey("masterVolume"))
{
LoadVolume();
}
else
{
SetMasterVolume();
SetMusicVolume();
SetSFXVolume();
}
}
public void SetMasterVolume()
{
float masterVolume = masterSlider.value;
myMixer.SetFloat("Master", Mathf.Log10(masterVolume)*20);
PlayerPrefs.SetFloat("masterVolume", masterVolume);
}
public void SetMusicVolume()
{
float musicVolume = musicSlider.value;
myMixer.SetFloat("Music", Mathf.Log10(musicVolume)*20);
PlayerPrefs.SetFloat("musicVolume", musicVolume);
}
public void SetSFXVolume()
{
float SFXVolume = SFXSlider.value;
myMixer.SetFloat("SFX", Mathf.Log10(SFXVolume)*20);
PlayerPrefs.SetFloat("SFXVolume", SFXVolume);
}
private void LoadVolume()
{
masterSlider.value = PlayerPrefs.GetFloat("masterVolume");
musicSlider.value = PlayerPrefs.GetFloat("musicVolume");
SFXSlider.value = PlayerPrefs.GetFloat("SFXVolume");
SetMasterVolume();
SetMusicVolume();
SetSFXVolume();
}
}
so they are saved in PlayerPrefs. so just . . . load them from PlayerPrefs and apply them. maybe even store them in a static class or something
I'm having trouble again 😶
Do I just copy the entire file or?
Cause to apply the PlayerPrefs I would need the SetVolume functions
you do not need to set the playerprefs in the main menu, all you need to do is load from PlayerPrefs and apply the loaded value(s) to your mixer(s)
I want to re-call start at the beginning of a battle in my Hiragana learning game. According to my research it's not possible since it can only happen once during a script's lifetime. What's a good way to re-initliaze my whole battle manager at the beginning of a fresh battle?
https://gdl.space/idutekotoj.cs
Take all the code in Start and put it in a different function. Then you can call that function in Start, or anywhere else you want
So, you could call Initialize or whatever you call it when a battle restarts
Or have some public method call start 
Oh I see, so a good way to go about doing it would be to create a bool isInBattle then use that isInBattle to initiate the desired code
Then when the battle is over, set bool to false
Absolutely cromulent C#, but I'd say it's bad practice to manually call a Unity message function
I got it to work with this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Audio;
public class NewBehaviourScript : MonoBehaviour
{
[SerializeField] private AudioMixer myMixer;
void Start()
{
float masterVolume = PlayerPrefs.GetFloat("masterVolume");
float musicVolume = PlayerPrefs.GetFloat("musicVolume");
float SFXVolume = PlayerPrefs.GetFloat("SFXVolume");
myMixer.SetFloat("Master", Mathf.Log10(masterVolume)*20);
myMixer.SetFloat("Music", Mathf.Log10(musicVolume)*20);
myMixer.SetFloat("SFX", Mathf.Log10(SFXVolume)*20);
}
}
There might be some redundent code but I'm happy it works
Thanks for the help Boxfriend
How come my text isn't populating? When I set it manually no issues, but in script it won't populate. Here's a snippet of the call:
void Start()
{
correctResponse.text = "Wrong!";
}
Is the correctResponse reference to the right object?
Yeah, that was my first instinct
You can click it in the inspector and it will highlight the object
Hmm, well, then is that object active at runtime, and no other scripts are referencing CorrectResponse text component?
I can double check but I'm pretty sure there isn't
Yeah I scrubbed through, nothing to my knowledge is referencing that object
Ahh I see what's happening...
My rudimentary answer checker is resetting the text on Update, what's a better way to handle the answer check?
private void AnswerCheck()
{
// This is our answer checker
if (inputField.text == "あ")
{
correctResponse.text = "Correct!";
// This resets the text field
inputField.SetTextWithoutNotify("");
correctResponse.text = "";
inBattle = false;
ExitBattle();
}
else
{
// TODO play a sound
correctResponse.text = "Wrong!";
inputField.SetTextWithoutNotify("");
correctResponse.text = "";
inBattle = false;
}
}
Hmm maybe when the player presses enter then it calls the answer checker? Rather than it actively checking for the answer
I have small script for patrolling enemies for my 2d game, but I'm struggling to fix something.
Basically I had the script in void Update() at first, but if I alt-tabbed the position of some enemies would mess up a little. so I then moved the script to void fixedUpdate() and it works perfect now but the movement looks less smooth
This is the script for the enemy movements
It's a little hard to see but the first 2 sets of enemies movements look less smooth than the rotating enemies
The rotating ones were made in void Update(), the rest are from the script above in void fixedUpdate()
!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.
well, yeah, FixedUpdate only runs 50 times per second
Even if you don't alt-tab, this will eventually get enemies out of sync when run in Update
When an enemy reaches its waypoint, the rest of its movement gets wasted
if it can move 1 meter this frame, and only has to move 0.1 meters, the other 0.9 meters are wasted
You could fix this by writing a while loop
Calculate the enemy's move distance, then use MoveTowards to approach the waypoint
Check how far you moved. If you moved less than your move distance, switch to the next waypoint and run the process again
Gotcha, thanks!
and sorry!
you might want to add a sanity check that breaks the loop after, say, 1000 iterations
so that the game doesn't freeze if you mess up
gotcha, I'll work on that then!
No worries ! Was just hard to see on mobile
Is System.Management not supported?
tried adding with dotnet command in terminal too
If it's windows only library prob won't see
its .NET
I get that
You could probably just do that if you get a compatible. Net version
So im not sure if its the animation settings or my code, but im trying to have an enemy walk/idle using a blend tree mixed with a script, but when trying to have him walk, he just plays the idle animation and never plays the walk animation
How could I instantiate a bunch of prefabs with their own color?
Instantiate one, then call a function on it that changes its color
What that function is depends on what kind of object it is, if it's a mesh or a sprite or whatever
Try debugging it by looking at the animator window while playing, with the character selected
You can see the parameters and transitions in real time
Ok will try thank you!
Well, according to the blend tree, he should be doing the walk animation, but it looks like its still playing the idle animation
I've got a flash card like-system, and I want to randomly assign the cards. So if the character "あ" pops up, it displays as one of the answers. How do I set it up so that it is random where that card is placed, and the other characters are random characters from an array of strings?
hello guys, i have this code for a score board and unity is giving me this error, can someone help me pls?
Did you assign Pountucao in the inspector?
Hey, quick question about this. Can I write the while loop in the update function or should I make a new function for it alltogether? Right now either the enemies aren't moving or I seem to make an infinite while loop each frame that breaks unity Editor alltogether
Show me what you wrote.
you need to sum up the distance you've traveled
does this line not work for that?
no, that just sets distanceMoved to that difference
it's not counting anything up
also, your loop isn't actually changing which waypoint you're going to
you want to move towards your current waypoint, then check how far you went
if you didn't move far enough, that means you reached the waypoint, so pick a new waypoint
repeat until you move far enough
How do I create an array of buttons?
if the condition in while is no longer met it stops working right? so wouldn't this if statement I just wrote below the while loop work for that?
float movementRemaining = speed * Time.deltaTime;
Vector3 position = transform.position;
while (movementRemaining > 0)
{
Vector3 movedPosition = Vector3.MoveTowards(position, points[currentPoint].position, movementRemaining);
movementRemaining -= Vector3.Distance(movedPosition, movementRemaining);
position = movedPosition;
if (movementRemaining > 0)
{
currentPoint += 1;
currentPoint %= points.Length;
}
}
transform.position = position;
This is what I was thinking of.
almost perfect
However, this might bang into some annoying problems with floating point precision. I'm just getting the Vibe(tm)
issue now is that the file doesn't appear until after I leave playmode
how do i do it?
Drag it in or click the drop down menu
Where you have the script assigned
Time to go through the essentials in !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
to the score text
Yeah your Score Texto is empty
float movementRemaining = speed * Time.deltaTime;
Vector3 position = transform.position;
while (true)
{
Vector3 destination = points[currentPoint].position;
Vector3 movedPosition = Vector3.MoveTowards(position, destination, movementRemaining);
// we reached the destination!
if (destination == movedPosition)
{
movementRemaining -= Vector3.Distance(position, movedPosition);
currentPoint += 1;
currentPoint %= points.Length;
position = movedPosition;
}
else
{
position = movedPosition;
break;
}
}
transform.position = position;
Getting dinner in a min so I need to run
you cannot do that, you would have to initialize the array in awake or start, why you have to do this is beyond me.
But the idea here is to break out of the loop once you fail to reach the waypoint
@swift crag I'm dumb and didn't know about Vector3.distance thanks for sharing what you had in mind
If you do reach the waypoint, subtract the distance you moved and try moving to the next waypoint
Well as described before I'm trying to randomize my flash cards
Randomize the answer*
I'm gonna rewrite a bit with the new knowledge and what you shared, will update in a bit how it went. thanks Fen!
what about now?
I don't know what your code does but I assume that should be correct
should be, but it is not working! i am desesperate with this
Show your code
Create an answer button class to do your bidding and you would have references and a list all in one.
[SerializeField] private List<AnswerButton> _answers;
Thanks I'll tinker with this
Hmm looks correct to my eyes, you're adding a point to the ScoreBoard.Pontucao then re-assigning the text on update
not a problem, thanks btw
Np
my code outputs .../Assets\SpawnCampGames/Docu...
is outputPath = outputPath.Replace('\\', '/'); normal to use to keep them uniform?
just feels a bit after-thought-ish
string outputPath = Path.Combine(Application.dataPath, filePath);
outputPath = outputPath.Replace('\\', '/');```
alrighty..
Yeah it looks jank but it works lol
was just about to check my save system cs public void Boot() { saveFilePath = Path.Combine(Application.persistentDataPath,saveFileName); _saveData = Load() ?? new SaveData(); } it uses persistent
isntead of dataPath
was curious if it did the same
Yeah that's good
i just never debugged it before
thats all i needed to hear
I implemented this and it works very well, thank you!
Hope I can figure it out on my own next time I run into an issue
It's a bit of an awkward problem!
someone else had a very similar question a few days ago
in their case they were overshooting the goal and then getting messed up
Hi ppl
how ya'll doing tonight
I have a few questions regarding OOP and game architecture
In general I never saw the reason for using classes and currently, i use them exactly like one would use C structs
But recently a friend that's been helping me told me that the way he would do it was making it highly composable using tiny classes, for example, in the card game I'm making what he would do is make each card a different class (it's a hearthstone like)
And that sparked a lot of self-doubt in me
Like, can I really make this work? Is my coding skills crap?
I always much preferred making things as simple as possible, and for me classes seems like an extra fluff that makes things harder to read
I really like the functional programming style for this reason, everything is just so simple and easy to read (for me)
sounds like he wants to follow SOLID
But, unfortunately, functional is not used as much as OOP in gaming ...
first one being Single Responsibility
What is SOLID?
should i know that to become a real game dev?
i think so..
its a fundamental way of structuring ur code
which gets more important.. the more advanced u get
i found this video really enlightening when i first heard of the concept ☝️ @remote osprey
thers really no wrong way to code imo.. if ur the only one (or 1 of 2) people working on it.. as long as u stick to a structure you're fine
always helps to know fundamental principles like SOLID.. esp when u share ur code w/ others.. go seeking help, or want to integrate someone elses code into urs
sure, u could think of it like that
its not a concrete type of solution
im 3 years deep in learning c# and unity.. and i still struggle at times about the concepts
but keeping them in the back of my mind helps me get going the right direction
so i dont end up with spaghetti at the end of the day
good luck w/ teh card game tho! i've wanted to do one for a while now.. but it seems too intimidating for me
especially when u start thinking about game-flow.. and balancing
Hmm so it's okay to do my own spagethi code for now?
Well one thing with unity is a lot of the work can be done in editor. Making everything in it's own class instance (assuming we are talking about making 2 card instances from 1 class) might not be too friendly for your artists and non coding peeps. This is where scriptable objects come into play and not everything is declared in code. It exists as assets.
Your tiny classes could be used as separate ways to like attach logic to a card.
lmao.. while u learn? sure
i wrote spaghetti for a while.. but the only way to get better at not writing it.. is to know when its happening lol
Yeah, I'm not working with anyone else, for now
I think that learning about Solid rn would just get in my way, if you know what I mean
Cause what's important is that I have my card game working
I can learn about solid in a smaller project later on
Especially since I'm a beginner at using Unity
i mildly disagree with that
Usually it's a lot easier if you can setup some work to happen in inspector. Although the suggestion your friend said kinda has me wondering what your setup is or what they really meant.
Every single new card definitely shouldn't be it's own class
maybe not focus on it.. but i would def read up on it..
It's cause, I would have to rework everything if I wanted to apply SOLID in my project
Seems kind of a hassle, tbh
noo.. just start from where u are..
i almost got everything working
dont go refactor everything for no reason
lol
care sharing some of ur code?
i'd like to see how ur working atm
Thing is, every card has a different effect when: played from hand, when drawn, when targetted, when attacked, when buffed from hand, when buffed, etc....
Sure, i can screen share if you want
!code nah, just use an external link
📃 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.
id just like to see what ur Card class looks like
like the main meat of the project lol
Nothing about this should require the actual card to be a different class. This is where composition would tie in. Attach logic that happens on each of these events
cool cool
Its honestly a bad suggestion to even make a unique class for each card.
Oh yes Composition is dope in Unity
So, (almost) every card will have it's own method anyway
except for cards that do similar effects
like summon a 5/5 minion with no effects
tbh thats the only case i reuse methods
Exactly, but with the suggestion of class for each card, you no longer can reuse methods because you've created a whole class purely for 1 card.
Composition would mean you just create a method of spawning minions, and attach that logic to a card. Now any card can spawn minions if it has the class to do so
Does anybody know how to resize the grid?
many scripts with single responsibilites
vs a big monolithic class w/ everything
ur script looks good tho..
Hmm so maybe I could use something like a WhenCardDraw class?
I mean, main problem to me is, i can't do something like DoDamage(x) because my Delegate doesn't accept parameters
I didn't find a way to put variable number of parameters through my delegate so i left basically one method for card
DoTween is perfect
I tried to do animations without it it was impossible
ur not lying..
i add it to every project i start first thing
DoTween, TMP, and Cinemachine
Do you have any suggestions or feedback?
public delegate void CardAction(Card card);``` why couldn't u use delegates that have parameters?
I would.. I'd use a UIManager
just like ur gamemanager..
I can, but not all cards use parameters
and call functions on it to update ur text and stuff
Anyone?
I don't want to have redundancies in each call
New to dictionaries, how come it is throwing an error that it answerKey does not exist?
Having some objects not use all the parameters is much better than not implementing this.
It gets harder for me to read the code tho
Which method is your code inside?
I honestly don't want to decipher a 10 parameter functoin that I'm using everywhere everytime
It's being declared before Start()
This is incredibly vague. "The grid", what grid? Is this a code question
Editor grid
Oh... am I not able to add it there?
"What method is that line in" is a hint to what the issue is
@south ruin the only tip i have is to only update ur UI when u need to...
like for example if u updating player health.. dont do it every frame..
instead, when you take damage for example, then you update the UI after you subtract from the health component or w/e
w/ a UI manager singleton.. it'd be easy to call a function UpdateHealthBar(newHealthValue);
Ahh thank you so much @eternal needle
Then make a class or struct for the parameter. It really shouldnt get so long, but even then it's just something you'll need if you want to make a lot of cards. Look at your current code, how in the future are you going to read through all of this when you have 50 different things that could be assigned to Call
That's actually a pretty nice suggestion, thanks!
ever heard of the <Summary> tags?
/// <summary>
/// Display text on the screen in real-time for debugging purposes.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="position">The position of the text on the screen.</param>
/// <param name="size">The size of the text.</param>
/// <param name="textColor">The color of the text.</param>
public static void RealtimeDebug(string text, Vector2 position, int fontSize, Color textColor, Vector2 widthHeight)
{``` for example
IDE powah 💪
at the end of that function u can call w/e functions u need to from the UI_Manager to update the values it initialized
it's nice, but I'm not particularly fond of this
Because to me it's still very hard to read when parameters start to stack up too hard
like in matplotlib, for example
I only remember because of use, but it annoys me and it just doesn't feel good to me
How do I access dictionary values at random?
This is the equivalent of what I am attempting, but with an array
// Random between two numbers to pick out the random Hiragana
int randomIndex = Random.Range(0, hiragana.Length);
for example, cs public void UpdateVisuals(int health, int stamina) { HealthText.text = $"Health: {health}"; StaminaText.text = $"Stamina: {stamina}"; } would be in ur UIManager script..
and then, in something like ur GameManager:
private void InitializePlayer()
{
player.health = 100;
player.Stamina = 100;
UIManager.Instance.UpdateVisuals(playerHealth, playerStamina); //now update the UI
}```
public void DamagePlayer(int damage)
{
player.Health -= damage;
UIManager.Instance.UpdateVisuals(player.Health, player.Stamina);
}```
thats fine.. everyone has their own way.. i'm just throwing out ideas here and there 🙂
what is Cthulu mean?
Talking with you guys made me realize that i'm ok
I was feeling terrible about my code haha
ur way above just ok
u didn't come in here.. saying why is this void not working..
lol
It's a cheap copy from Hearthstone's Cthun haha
and u have a singleton GameManager..
Yes
i mean everything in ur script is very acceptable
there can only be one..
My code is chonk
hence why its a singleton
Nice single chonk
Can you guys tell me which one is a better practice?
Type 1:
using UnityEngine;
public class StateCheckTest : MonoBehaviour
{
[SerializeField] private GameObject winLoseStateScreen;
private WinLoseStateCheck _winLoseStateCheck;
private bool isAlive;
private GameObject WinLoseStateScreen(WinLoseStateCheck state)
{
switch (state)
{
case WinLoseStateCheck.Win:
winLoseStateScreen.transform.GetChild(0).gameObject.SetActive(true);
Debug.Log("You won");
break;
case WinLoseStateCheck.Lose:
winLoseStateScreen.transform.GetChild(1).gameObject.SetActive(true);
Debug.Log("You lose");
break;
}
return winLoseStateScreen;
}
private enum WinLoseStateCheck
{
Win,
Lose
}
}
Type 2:
using UnityEngine;
public class StateCheckTest : MonoBehaviour
{
[SerializeField] private GameObject winScreen;
[SerializeField] private GameObject loseScreen;
private WinLoseStateCheck _winLoseStateCheck;
private bool isAlive;
private GameObject WinLoseStateScreen(WinLoseStateCheck state)
{
GameObject activeScreen = null;
switch (state)
{
case WinLoseStateCheck.Win:
winScreen.SetActive(true);
activeScreen = winScreen;
Debug.Log("You won");
break;
case WinLoseStateCheck.Lose:
loseScreen.SetActive(false);
activeScreen = loseScreen;
Debug.Log("You lose");
break;
}
return activeScreen;
}
private enum WinLoseStateCheck
{
Win,
Lose
}
}
dont get urself muted @remote osprey
Sorry 😦
no worries.. i accidently muted myself the other day trying to post the Unreal discord link to a troll that was asking why he was even here.. b/c unity scked and unreal was better
which one are u leaning towards?
Garsh, that's rough
Anyway, i should get going
i'm already spamming here
Thank you for your help!
good luck mate 👍
I like having compact code, which is Type1, but for some reason it also feels like a shit code
theres a balance game at play..
on one extreme u have syntax sugar (pretty short code)
and the other extreme is readibility
So basically If I want people to like me, I should go with Type2
the easier it is to read.. the more collaboration you can expect
if its a chore to go thru code.. (even if its nice and tidy) some people wont
Gotcha, cheers
Type 2 is better imo
I wouldn't call type 1 "compact"
besides depending on how often u call the WinLoseStateScreen, you have GetChild calls in there.. which ur second one does away with
It has these enormous brittle lines in the middle
winLoseStateScreen.transform.GetChild(0).gameObject.SetActive(true);

does Collider.OnCollisionEnter(Collision) work without rigidbodies?
nope
damn
This is the worst of both worlds: you wind up with long lines of code that randomly blow up in your face
Dictionaries use keys as opposed to indices. You can work around this with linq and ElementAt
I need to go back and more thoroughly test how character controllers interact with the physics system
I remember getting some interesting results
like a CC entering a non-rigidbody'd trigger collider produces messages...eventually
it was inconsistently timed
was it u i was talkin to yesterday about kinematics and MovePosition?
its not for a character collider i was wanting to do collision detection with a custom script thats like rigidbody but only has gravity
or was it navarone?
Depending on what you want, a spatial query might be what you want.
ayoo
yeah I did a ghetto work around where I used my hiragana string array as the randomizer
type 1 depends on the exact order of children
Hi i was just testing out the default unity character controller third person scene sample and it works fine on the default character, i swapped out the mesh of the default robot with my own character and it sort of works apart from the fact that when the character jumps it jumps infinitely into the sky, anyone used that defaut asset for testing and knows what that could be?
Here are all of the places that I use GetChild in my medium-sized game project
A blog about game development, programming and design.
ig i dont have any reason to skip out on rigidbodies
One of them is picking a random child of a transform
i found this yesterday.. its pretty useful to gather info @ a glance
because I just parented all of my spawn points to a single object
The other two are explicitly for effects that apply to all children of an object, one at a time
That's it. I only use GetChild 3 times in about 26,000 lines of code
'cos you almost never need to use it!
Gotcha, It can get messy and break code quite easily so I should stay away from it as much as I can
Right. In general, if you can directly reference something, that's what you should do
So prefer a direct reference to MyComponent over storing a GameObject and then using GetComponent<MyComponent>()
and prefer direct references to objects over referencing a parent and getting children by index
The exception is if the individual children don't really have meaningful differences
VerticalFader is used to fade in a list of UI elements. The whole point is that it shows one at a time based on hierarchy order, so it makes sense to use GetChild there
In your case, the hierarchy order is a coincidence
If you do genuinely have a situation where you need to use the third child of an object, then yeah, use GetChild -- but that's quite rare
reducing these "coincidences" makes your code more robust
I used to do this a lot
public GameObject myPrefab;
...
GameObject instance = Instantiate(myPrefab);
instance.GetComponent<Florp>().Foo();
now I just do this
public class MyCoolPrefab : MonoBehaviour {
public Florp florp;
}
...
[SerializeField] MyCoolPrefab myPrefab;
...
var instance = Instantiate(myPrefab);
instance.florp.Foo();
I only have 7 serialized fields that store a GameObject. Most of them are for a cursor system where I am literally just moving an object around
...and one shouldn't be serialized, whoops
Gotcha, thank you for the very detailed explanation again
no prob (:
(even worse: instance.transform.GetChild(0).GetChild(1).GetComponent<Image>().sprite = whyyyyyy;)
MyCoolPrefab can later make its fields private and provide methods to do specific things
https://gdl.space/puweyepupu.cs
This used to just be a few public fields
that instance is like: "guys, lock in"
it's used to display a single button in a control hint
I added the methods when I realized I wanted to put logic into it, instead of having another component just reach in and mess with its public fields
public void Press()
{
sizeGoal = 0.8f;
returnTimer = 0;
}
public void Release()
{
sizeGoal = 1f;
returnTimer = 0;
}
public void Raise()
{
sizeGoal = 1.25f;
returnTimer = 0;
}``` ? whats this Fen ?
They're used to make the icons react to player input
...having this happen on the control list wasn't exactly a design goal
but hey, it works
Build it once, use it many times (:
i should probably hide the splash screen action lol
Build it once, bug, build it twice, new project, port it over, crunch time, forget about it, built it again, forgot you had it 
thats more like it
both the UI and the settings system have been copied from project to project
growing stronger each time as I realize the how I blundered last time
what sucks is that, when i go back to an older project now, i realize that i've got the old janky system
This reminds me that I need to make a pause ui for my demo. I don't wanna
How do I use the other values of the Random.Range? My intent is to use those values to assign the other Button Text in my Hiragana learning game
// Random button text will be assigned the hiragana[randomIndex]
int randomInt2 = Random.Range(0, 4);
answerButtonText[randomInt2].text = answerKey[hiraganaArray[randomInt]];
"other values"?
Say you get a random value of 1, how do I get 2-4?
ah, you want to fill in the other buttons
Correct-a-mundo
Could loop, use rand as the start index, then wrap i around the length 
for (int i = 0; i < 4; ++i) {
if (i == picked)
continue;
// do stuff
}
Alternatively, don't skip: just do whatever you want to do for the correct answer there
next up: Duff's device
Okay this is where it gets tricky... how do I ensure I'm not using the same value twice?
for (int i = 0; i < 4; ++i)
{
// Set the text randomly between 0 and 4
answerButtonText[i].text = answerKey[hiraganaArray[Random.Range(0, 4)]];
// If they're the same
if (answerButtonText[i].text == answerButtonText[randomInt2].text)
{
}
// If we encounter randomInt2 we just skip it
if (i == randomInt2)
{
continue;
}
}
Pick the random number before the loop
Ah, I see what you want
You want to shuffle a set of numbers.
The simplest way to do this would be to make a list of numbers
pick a random index, use that number, and remove it
repeat until the list is empty
Whew this is getting tricky haha
List<int> choices = new() { 0, 1, 2, 3 };
while (choices.Count > 0) {
int listIndex = Random.Range(0, choices.Count);
int chosen = choices[listIndex];
choices.RemoveAt(listIndex);
}
bah
like so
This will give you the numbers 0, 1, 2, and 3, in a random order
The Fisher–Yates shuffle is an algorithm for shuffling a finite sequence. The algorithm takes a list of all the elements of the sequence, and continually determines the next element in the shuffled sequence by randomly drawing an element from the list until no elements remain. The algorithm produces an unbiased permutation: every permutation is ...
Indeed - Fisher-Yates is great to create an entire shuffled list
I use it!
I remember having to prove that it worked back in a randomized algorithms class in grad school
I have an enum in a class and a function that uses it```public enum Direction
{
Forwards,
Backwards,
Left,
Right
}
public void InvertFormation(Direction direction)
{
}```
In another class calling the function, why does this not work:
formation.InvertFormation(formation.Direction.Backwards); //error
but this does?:
formation.InvertFormation(Formation.Direction.Backwards);
I thought that was only for static member attributes?
because enum belong to the class not the instance
enum is static member of the class
so an enum is automatically static?
const but const is static in c#
okay I understand, thanks
Not so much that it's static, it's a Type. It's like having a class inside of a class
Hmm this makes less sense to me.
yes -- nested types are a distinct kind of member
If you declare a type inside of another type, you've got yourself a nested type.
Direction was defined in Formation. It's not a member of an instance (formation) thus why you'd use Formation when using the enum value.
The nested type does not belong to a specific instance of the enclosing type, yes
just like how static fields don't belong to a specific instance of the type
hello. this is a semi-long script so i would understand if it takes awhile to get help. i have asked chatgpt literally over 20 times and every response doesn't work. im wanting to update the text to make the count +1 (1/5, 2/5, etc) everytime i complete a chore for my horror game. however, choresCompleted never updates past the completion of the first chore.
i hope using pastebin is alright here. i dont remember the other sites. https://pastebin.com/Mpjf4Xzr
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 dont think a float choresCompleted makes sense unless you will display "total: 1.2345/5 chores completed"
btw i guess choresCompleted should be shared across instances
so just make it an int?
quick question just to be sure, does GetComponentInChildren just go straight to the children or does it look through the object its called on first? ik it sounds obvious but you really never know
actually thats a stupid question, of course thats what i should do
yes it looks for the component on the same object as well
i knew it
and is this gpt code?
choresCompleted += 1;
Debug.Log("Chore Completed!");
Debug.Log("Chore Completed! Total chores completed: " + choresCompleted);
isChoreCompleted = true;<---?
choreCompletedCount.text = "Chores Completed: " + choresCompleted + "/5";
timer = 0f;
isInteracting = false;
isChoreCompleted = false;<---?
progressBarFill.Value = 0f;
never trust the way programmers name things
wish we had a version of it where it can skip the first but oh well
that 2nd Debug.Log was gpt, yes. and my code is horrible lol
thats because you're using gpt
oh i just saw the two isChoreCompleted's
incorrect - i didn't use gpt for all of it. my code is horrible. my statement is correct
i was looking for a way to get the transform of the child of an object, in which case therell always be only one child, and i just want to avoid using the find object by name function bc that messy as hell
im not going to say i didnt use gpt but i dont use it for the whole script, only when i run into issues
why not just link the reference in the inspector directly?
https://docs.unity3d.com/ScriptReference/GameObject.GetComponentsInChildren.html
This method checks the GameObject on which it is called first, then recurses downwards through all child GameObjects using a depth-first search, until it finds a matching Component of the type T specified.
dfs confirmed
and you just have one child..
gpt did tell me however to reset the isChoreCompleted variable after the text is updated.
true i could do that i just forgot
https://unity.huh.how/references/singletons
you may need this
hmm ill take a look at it
know what "static" is and what it does
why is OnMouseButtonUp() being called like 9 times?
using UnityEditor;
using UnityEngine;
public class Slot : MonoBehaviour
{
[SerializeField] private bool hoveringOver;
[SerializeField] public bool slotFull;
[SerializeField] GameObject itemInSlot;
GameObject player;
void Awake()
{
player = GameObject.Find("Player");
}
void Update()
{
if (this.transform.childCount > 0)
{
itemInSlot = this.transform.GetChild(0).gameObject;
slotFull = true;
}
else
{
slotFull = false;
}
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
if (Input.GetMouseButton(0))
{
// Debug.Log(Input.mousePosition);
if (Physics.Raycast (ray, out hit, 100, 1 << 5) && hit.transform.tag == "InvDropArea") //UI Layer only
{
Debug.Log(hit.transform.name);
if (Input.GetMouseButtonUp(0) && slotFull)
{
Debug.Log("trying to drop");
itemInSlot.SetActive(true);
itemInSlot.transform.parent = null;
itemInSlot.transform.position = player.transform.position + new Vector3(Random.Range(-0.5f, 0.5f), 0, Random.Range(-0.5f, 0.5f));
itemInSlot.GetComponent<Item>().ResetItemIcon();
itemInSlot = null;
}
}
else
{
Debug.Log("Not over drop area!");
}
}
if (Input.GetMouseButtonUp(0))
{
Debug.Log("up");
}
}
void OnMouseOver()
{
hoveringOver = true;
}
void OnMouseExit()
{
hoveringOver = false;
}
}
what makes you say it got called 9 times
also you should avoid GameObject.Find
in the console it printed "up" 6 times
are you sure you don't have this script on multipleobjects?
if you have n instances then update runs n times, so print n times
Do you've got 6 objects with this script attached?
it's actually 8 different objects with this script but yeah I do see your point now
weird that it only printed 6 times and not 8, but I get why it printed more than once now
How can I add an external library to a jslib file?
I want to add the discordsdk javascript library to a jslib for my webgl application, is this possible?
jslib is nothing more than a way to call js functions, should assume is the same way no matter what
this is what im looking for, how can i do this in jslib?
i dont understand this is just regular imports in JS file just embed whatever js you want on the html page no?
unity webgl build is just embedded inside an html file
sorry im not very experienced with javascript, however after i embed the js file containing the library i want to use, how can i access it through unity? do i just call it from jslib?
I haven't played around jslib too many times but you should just be able to call any js function through unity, with jslib thats what is for basically
@latent magnet not sure if you seen this yet
https://docs.unity3d.com/Manual/webgl-interactingwithbrowserscripting.html
yea i did read it
gotcha
i just had a problem with embedding the js file
what is it you're trying to do exactly?
depend on your hardware
that doesn't explain what you're trying to do and fankly don't feel like asking 20 questions
for vr...
you can set the fixed update time in setting btw
you can setup a timer and change the fixed dt back to 0.02?
is there something you're actually trying to solve with this? Because this arbitrary value would likely fail in a ton of cases. I think it would be better if you introduced a speed multipler, and then your custom fixed DT can be like Time.fixedDeltaTime * multiplier
also stuff like rigidbodies wont respect this custom number, so it really does matter what you're using it for
50fps constant? theres nothing you can do if the game is only running 50 frames yet i assume you really mean 50 fixed updates per second
then dont try to change fixed delta time to compensate. Either interpolate the object (which is a setting for rigidbodies) or write your own interpolation if this isnt a rb
a number multiplied by another number. Though i guess it doesnt fully matter if your only use case was fixed delta time. It just really doesnt make sense to use it though, fixed update still runs only 50 times a second. You wont suddenly be running more code
so Ive got a script which lets an object follow the mouse but how do i change what axis the mouse rotates around im using ScreenPointToWorld too
It would help if you showed the script
alr
void Update()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
transform.right = direction;
}
!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.
void Update()
{
Vector3 mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
Vector2 direction = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
transform.right = direction;
}
sphere mesh not visible?
Not a code problem, but I imagine that's not the default sphere and it's either too big or small
I'm not at my IDE right now, but is transform.right = direction even valid?
transform.right refers to the right-facing Vector3 direction respective to the local transform. I don't think setting this value to another one is meaningful, but I can't verify without my IDE.
Yes
Can you even set transform.right? Its a fixed value of the transform and you cant magically change the pivot, can you?
I just asked that same Q. Check the docs vertx posted
It runs a rotation function
In any matter, my intuition is to change transform.right to transform.up
If you want to reverse it, just multiply the vector by -1
Ahh, my bad. Good to know. I thought always transform directio nvalues are read only 🙂 good call here
I thought that too tbh
Can I set my mesh collider to stick to the shape of my mesh? I wanna be able to go through this ring without it colliding in the center.
So it sticks directly to the ring and not covering the middle as well
There is a setting so that it can have holes, i think its named concarve
Just know that physics does not like that, i would split it into 2 half rings
hello im having a problem where my player doesnt orientate towards where my camera is facing. as in like the character parent does but the model as a child of the parent. sorry i dont know what info to give
looking at your hierarchy, your playerObj will not rotate if you rotate the camers unless you do so in code.
As for what info to give. This is a code channel so we expect to see !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.
Can you make a better screen shot of your left top like hierarchy
does anyone know of a way i can make an object disappear when the camera gets close to it? im designing a desert level and id like to have a small oasis that dissapears when the camera pans over towards it
Well something with making a sphere around the player and a if statement when sphere touches object object gets destroyd
Raycast from Camera, check distance, disable oasis renderer
Yea but that you can walk backwards to the obj
Or its a fueture
but is there a way to do it where it slowly fades in and out of view? id like the oasis to re-appear when the camera pans away
a distance check doesn't care about which way you're facing..
and this is in a top down view
fade out the alpha on the material
or use a shader to dither it out (like Mario Odyssey)
Is it for if a player enters a home?
nah just an environmental thing
i want it to slowly fade away like the closer you get. not all at once
so closer you get the more of it fades away
Perhaps you might like to give FULL information when asking a question, not drip feed it
Yes.. I understood that and gave you two solutions
Well gpt can be your best friend
but if i fade out the alpha wouldnt it do it ALL at once?
Yes it would
please do not recommend GPT unless you are going to fix it's shit
Obviously it would do what you tell it to... the word "fade" means over time..
lol, stop replying, you've been wrong with almost everything you've said
hold on ill try and record what i mean lol
You don't need to record everything
Its great for stuff so i dont have to search it if you have enough exp you can see the mistakes in the code
You set the alpha value depending on the distance away from the oasis
you don't set the value directly to 0
but you have no idea if OP has the exp, do just don't
And no i wont you peter griffin yellow smurf looking bald ass soldier
It's Homer Simpson, numbnuts
I know but the meme
¯_(ツ)_/¯
no i get what youre saying with the fade. do it as a slow decrease. but the oasis i want it to fade top to bottom?
and for good reason
<@&502884371011731486>
You'd need to do this with a shader then
Stop being a troll
ah i see. so to get this sort of effect?
i dunno why im so bad at explaining today lmao
Yeah
dang. might just go for the alpha fade then. have it all at once if i have to mess with shaders
Ok i will just say my question i had what are quaternions
use the gpt you like so much 
You can always come back to this later and improve it to what you want, doing the fade now would get it done so you can carry on making the game
Pls dont be a troll
<@&502884371011731486>
thats a fair point. so a slow alpha fade with a collider check?
no need for a collider
how would i make it check to see if its close enough to fade the alpha?
This, but with the fade instead of disabling the renderer
thats what i thought. wouldnt the check be done with a collider?
No
!warn 570214452989919235 Don't post off-topic, don't troll on the server. Read #📖┃code-of-conduct
itsluukgamer has been warned.
oh how would i check distance then?
... raycast
well, not even that
distance between player and oasis transforms
google -> unity how to get distance between transforms
will do. thank for the help
btw, it's fairly trivial to fade the alpha of a texture in any direction you want
it is?
google -> unity how to fade the alpha of a material
when i program i usually just put a bunch of if statements into update. but doesnt that mean that every if statement is being checked none stop? that sounds pretty inefficient computing wise. so is there a way to make it so an if statement is only being checked when needed rather than 24/7, or is that a pointless gesture?
but doesnt that mean that every if statement is being checked none stop?
Yes
that sounds pretty inefficient computing wise.
It is, you don't want every script running Update, you only want it when it's needed
You want to learn about events, delegates, etc.. things that listen and are called when needed
could you maybe redirect me to a newbie friendly source?
event is more inefficient than regular function call...
but it easier to maintain and read
hm, then what do you suggest?
like just having a shit load of if statements in update works just fine for me, but i would like to improve coding wise xD
it's about when to call the method..
reminder, default input system does just that and polls your input
If you really have things that need to be checked every frame then there's nothing wrong with the if statements. Modern CPUs can do billions of calculations per second, bunch of if statements aren't going to make a dent in that. If you have things that don't need to be checked every frame but e.g. when values change, you'd typically use events and properties: https://learn.unity.com/tutorial/events-uh and https://learn.unity.com/tutorial/creating-properties
every single update loop I have some bool to check if I return early or not
thanks :) but is there a way to know where the sweet spot is? i guess for smaller project it would be irrelevant to use anything else than regular if statements, or?
experience
dont have a lot of that lol
yet
ask yourself - > "does this need to be checked every frame?"
size of project doesn't matter
The rule of thumb is, does this thing inherently need to be checked every frame, or is this something that happens in reaction to something else?
I say the best comparison to really get an idea is through the default input vs the new input system.
Polling vs events
For example you don't need to check every frame if the player's health is below 0 to show a game over screen, you can check that only when the player's health changes
i recall seeing something about making it only check once per second rather than once per frame, but i think that involved coroutine, which is more costly computing wise rather than just having a bunch of if statements in update?
No it isn't
@keen dew it isnt? hm, ive just seen some people saying coroutines arent very resource friendly
ok, you took that too literal
"Does this need to be constantly checked? Or does it just need to be checked/ actioned when something else happens/ a button is pressed?"
Really, the whole discussion is about micro optimizations. There's very little performance difference and to really achieve such a difference between checking some bool every frame.
or some minor comparisons. Now, if you were to do some calculations every frame where you would only need to do it once per property access, that's something you can consider.
im a bit of a perfectionist, but i mostly wanted to do it to learn how to do it better
👆 first worry about getting the game done, if at some point you find that the game runs slow you can profile and optimize the actual thing that needs it
The more relevant thing to care about is Clean Code and maintainability.
A long Update method with a bunch of if statements becomes harder to deal with
true
but i find it a little hard to do "clean code" when im the only one looking at it
then everything looks clean to me xD
because you're a beginner.. you need to keep doing, learning, reading.
thats fair
I'm having problems with the Update loop continuously running "HitTarget()" - I've narrowed it down from the other scripts so "Bullet()" is only being called once as it should, but the impact effects duplicate until the "Target" has finally been destroyed.
How would i go about diagnosing this further if you can't spot an obvious mistake?
you could do various debug logs between everything to see if they give you the correct results
thats usually how i hunt down something that isnt working that i cant find
its a bit tedious tho
just add target != null to the if statement (which, for some reason, you set to null twice)
you really should learn to use the VS debugger. It makes life so much easier
probably more efficient than what i do xD
I was using debug logs to narrow things down to this 😇
there is nothing better than stepping through your code and seeing the changes line by line
I started adding more "= null" when I was debugging, once I've found the fix (testing your suggestion now) I'll clear it up again
I still have a collection of barn animals I use for my debugging which I've a habit of doing from working with some other languages
I use VSCode but I'll definitely look into that - will it help with odd loops like this?
absolutely
but is having a shit load of debug logs the best way to do that? im thinking it probably isnt. but thats just how i have taught myself to do debugging :|
although the VS debugger is, afaik, much better than the VS Code one
stepping through code makes stuff like statemachines rediciously easier to debug
but I will still debug log stuff that runs in update loop like constant positional updates
the problem with debug.logs is they only show you what you think you need to see. The debugger will allow you to see anything\
With the change - if (dir.magnitude <= distanceThisFrame && target != null)
havent really thought about it like that before
biggest problem with debug.log, thay are based on, usually incorrect, assumptions
tbh, imao, at the same time you are learning 'Hello World' you should be learning how to use the debugger. Would save many, many people a great deal of pain
you have a seriuous problem with your spawner. You are spawning from gameobjects not from prefabs
As far as I'm aware I create the prefabs in Unity and that's what I'm instantiating. I'll add it to my list though 🖖
look at the names. what you are doing is, in effect.
gameObject = prefab;
loop
gameObject = Instantiate(gameObject)
I appreciate it but trying to configure VSCode is taking up my brainspace so I can't make use of what you're saying right now. Thank you though.
If anyone knows of a better guide than this one, please do share - nothing is matching what I see in VSCode and suggests I need to do some JSON work... 🤷♂️
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Is there a simple way to delete the last char of a string?
@karmic kindle Here's the tutorials you should need
var foo = "bar";
var ba = foo[^1];
Or
var foo = "bar";
var ba = foo.Substring(0, foo.Length - 1);
The former probably won't work in Unity, but it's worth a shot.
sure
s = s.substring(0,s.length-1)
I love you, ty
how can i make it so that i can have something trigger at a value and a multiple of a value? eg, (if value 1 = value 2 (and value 2 x2, x3,x4 etc etc))
What?
You want to specify a base value and trigger code when a given value is a multiple of it?
modulo
Yeah, pretty much use a modulo, I guess?
Or division
var baseNumber = 5;
var currentNumber = 8;
var isMultiple = currentNumber % baseNumber == 0;
aight thx
modulo cooler than division tho
Not sure how division would work here. Maybe if you check for decimals but that seems unnecessarily complex
hey guys, what would i use to create the same effect as this video in relation to the pointing of the gun and arms. I cant put my finger on how the game does it. Looks almost like the arm, hand and gun are all seperate sprites? I have a look at script that allows the head to point at the curser
This is the compressed video but its kindof blurry
more of a topic for #archived-game-design or #💻┃unity-talk but yes they are independent parts of sprites
terraria is a good example too
If the base value is a float for example
oh really? thank you. I think its just confused me as the look at script works by pivoting around the pivot. I would suppose the pivot for the hand would be the end of the gun and then the pivot for the arm being the joint of the shoulder
But how would you write it then?
If floats were checked then there would also need to be approximation
i animated my enemy with 2 8x8 sprites, but when it swithes to the other sprite, it is not aligned at all with the original sprite
im sorry,how would i use this to my advantage
Okay, so I have Debugging configured and I'm looking at the loop in VSCode, I've set the breakpoints and I'm able to step in etc... but what am I actually looking for?
you need to slice the sprite up for one, but if you want to swap out weapons on the sprite quickly you'd use this
there's probably more tools around but I've not really toyed with them
This is the issue with my code & link to the script.
ahh okay, ill give splitting the sprites up. Do you think both hands should be in the same sprite. On is on the handle and one is on the end of the gun
i would assum keep them the same sprite
then put pivot point on the handle part
if you can flip sprites I'd do it as it just saved time
okay ill go give it a try, thank you
https://docs.unity3d.com/Packages/com.unity.2d.animation@8.0/manual/ex-single-skinned-sprite.html
They have skinned sprite tools too so I'd look aroudn in the 2D animation package
Just an example of what I meantcs float xp = 35f; float xpPerLevel = 10f; int newLevel = Mathf.FloorToInt(xp / xpPerLevel); if (newLevel > currentLevel) Debug.Log("Leveled up");
Modulo probably makes more sense for the OP though
Is this the right/better way to do it?
I've found out that this is where the bug is - the impactEffect is put as a child object and with any "time" assigned to it, the whole script loops. Any thoughts/advice on why? Essentially this started because I refactored my targeting script, so it has always had a timer in it and worked fine.
{
if(impactEffect)
{
GameObject effectIns = Instantiate(impactEffect, target.gameObject.transform);//, transform.rotation);
Debug.Log("Destroy impact effect");
Destroy(effectIns, 0.5f);
}
}```
