#💻┃code-beginner
1 messages · Page 124 of 1
[SerializeField] private GameObject interactable;
[SerializeField] private GameObject hittable;
Do i do like this? Or is this bad
no, just make it true at the start of Start
and like i try to get the component
[SerializeField] Item item; //works
[SerializeField] IInteractable item; //does not```
Yes. After the coroutine has ended
But i have to attach this script to multiple gameobjects, like zombies, items, not only items.
Don't serialize by gameobject type. You want to serialize by the actual type (the primary object)
ty
So what if i make a class by the name of "Things" and zombie class and item class inheritance from it.
So i serialize field like this: [SerializeField] Things interactable;
[SerializeField] Things hittable;
so i can attach a zombie or an item
is it good?
I'm pretty new to coroutines, I'm trying to fade out all wall pieces at once but this does it slowly one at a time. Is there a way to make it so it fades them all out at the same time?
Maybe the yield is in the wrong place?
well look how you're iterating. You're going through one wall at a time and fading each one in turn
I wouldn't call it things, as that doesn't really describe it well
it was an example
How should i fix this?
OK In that example then, I'd say not good.
you want something like:
float alpha = 1;
while (alpha > 0) {
alpha -= Time.deltaTIme * speed;
foreach (GameObject wall in walls) {
// set the alpha of each wall to the curernt alpha
}
// wait one frame
yield return null;
}```
see how the loops are switched?
Right, you'd want to stick to inheritance in this case for what you're asking. Interfaces for the most part should work similarly, but that support is through serialize references because you still need to be explicit about the type.
ahh i see, ill try that out
how should i name it?
Inheritance is good, and you can give them sub references to specific data stacks. Serializing all of that is AOK.
But your base class should make sense to someone without drilling into deeper context.
So InteractableBase and using that for doors, switches, chests etc makes sense. NPCBase would likewise do the same for NPCs. They could also derive one later deeper if you wanted common overlap.
The problem with Things is it isn't clear what it is or is to be used for. Is it used for UI? That's a thing. Input? That's a thing too. Is it the top or bottom of an inheritance stack? Anything that leads you to automatically answering those questions is good in practice.
That said, using inheritance and serializing it is perfect good in this case (imho).
ooh okay, now i understand, thank you
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerEquipment : MonoBehaviour
{
public PlayerScript PlayerScript;
public Animator HelmetAnimator;
public List<SpriteRenderer> EquipmentSprites = new List<SpriteRenderer>();
public List<RewardScriptableObjects> Equipment = new List<RewardScriptableObjects>();
public SerializableDictionary<Stat, float> Stats = new SerializableDictionary<Stat, float>();
public void Start()
{
SetStats();
}
[ContextMenu("Generate Stat")]
private void GenerateStat()
{
Stats.Add(Stat.Damage, 0);
Stats.Add(Stat.Health, 0);
Stats.Add(Stat.Speed, 0);
}
public enum Stat
{
Damage, Health, Speed,
}
public void SetStats()
{
SetStat(PlayerScript.Damage, 0);
SetStat(PlayerScript.HealthBar.MaxHealth,1);
}
void SetStat(float Stat, float StatNum)
{
Stat = Stats[0];
int EquipmentNum = 0;
foreach (RewardScriptableObjects EquipmentPiece in Equipment)
{
if (Equipment[EquipmentNum] != null)
{
Stat += Equipment[EquipmentNum].Stats[1];
EquipmentNum += 1;
}
else
{
EquipmentNum += 1;
}
}
}
}
Stat += Equipment[EquipmentNum].Stats[1];
.Stats accepts 0 but doesnt accept 1 for some reason
Are you ever calling GenerateStat
btw you should rename your variable
public PlayerScript PlayerScript;
Hi peeps, I want to get a position of my player in my enemy script so it can taregt the player. whats the best method to get the players position?
it can make your script failed to compile if you are trying to access static variable in future eg singleton
[SerializeField] private GameObject interactable;
[SerializeField] private GameObject hittable;
private void Player_OnSelectedInteractableChanged(object sender, ThirdPersonMovement.OnSelectedInteractableHittableChangedEventArgs e)
{
if (!interactable.TryGetComponent<IInteractable>(out IInteractable interact)) return;
if (e.selectedInteractable == interact)
{
ShowInteractable();
}
else
{
HideInteractable();
}
}
private void Player_OnSelectedHittableChanged(object sender, ThirdPersonMovement.OnSelectedInteractableHittableChangedEventArgs e)
{
if (!interactable.TryGetComponent<IHittable>(out IHittable hit)) return;
if (e.selectedHittable == hit)
{
ShowHittable();
}
else
{
HideHittable();
}
}
I did something like this
because i want the deadbody of the enemy to make show up a canvas when the interact ray cast is touching an Interactable.
yes but not through code tho
and btw is that from tranformice ?
Works perfectly, thanks boss. you're a god amongst men
you can't access the indices of a dictionary if you've not created that many entries, so make sure you're appending the values first. Also ye
called the method, still getting the error. also u got my respect
no wait you're accessing a dictionary by the keyvalue of a integer
ok wait you're accessing it wrong
Your keys are references it seems actually looks like a enum
What type is Stat
public enum Stat
{
Damage, Health, Speed,
}
public SerializableDictionary<Stat, float> Stats = new SerializableDictionary<Stat, float>();
ok right why I'm confused
enums are technically integers, but you want to be accessing by the enum type
the key is enum not integer, safety checking will block you
btw why you dont use an array to store the data?
ohhhhhhhhhhhhhhhhh
I forget if you can directly access the kvp by index, but you need to foreach it
assuming you want to do it how you're doing it
public float[] values
float x=values[(int)SomeEnum];
ok right, you can iterate over a c# dictionary but through foreach iteration
same with hashset surprisingly
void SetStat(float Stat, float StatNum){
Stat = Stats[0];
int EquipmentNum = 0;
foreach (RewardScriptableObjects EquipmentPiece in Equipment){
if (Equipment[EquipmentNum] != null){
Stat += Equipment[EquipmentNum].Stats[1];
EquipmentNum += 1;
}
else{
EquipmentNum += 1;
}
}
}
```i wonder what it is trying to do, have you clipped the code?
ok hear me out
i got a list which has a scriptableobject
each scriptableobject has a dictionary of stats
enum, float
i need to add the stat.damage ( lets say 10 damage ) to the player base Damage
player also has a dictionary of the same type
you miss the point your foreach gives you EquipmentPiece but then you go and use Equipment[EquipmentNum] for exatly the same thinhg
send a code (with how you think it would look like) than explaining what you want to happen
just to remain you that
public void Set(float a){
a=10;
}
float b=0;
Set(b);
Debug.Log(b);//b is still 0
First fix up the params such that
void SetStat(Stat stat, float statNum)
If you're going to continue using enum with dictionary
public void SetStats()
{
// Setting Stats for the player
SetStat(PlayerScript.Damage, Stat.Damage, RewardScriptableObjects.Stat.Damage);
SetStat(PlayerScript.HealthBar.MaxHealth, Stat.Health, RewardScriptableObjects.Stat.Health);
SetStat(PlayerScript.moveSpeed, Stat.Speed, RewardScriptableObjects.Stat.Speed);
}
void SetStat(float Stat, Stat PlayerStat, RewardScriptableObjects.Stat StatType)
{
Stat = Stats[PlayerStat]; // first set basic stat
int EquipmentNum = 0; // for the loop
foreach (RewardScriptableObjects EquipmentPiece in Equipment)
{
if (Equipment[EquipmentNum] != null) // check if item is equipped
{
// equipped = give item stat to player stat (adding up)
Stat += Equipment[EquipmentNum].Stats[StatType];
EquipmentNum += 1;
}
else
{
EquipmentNum += 1;
}
}
}
you can debug.log to see if the player damage got changed
again please rename your variables....
ok gimme a sec
Stat = Stats[PlayerStat] - this overwrites the value of your float Stat parameter (those should be in camelCase, not PascalCase), so the parameter itself is not needed
it's also a value type which you aren't returning so there's no actual usage of it in this code
which refer to ^
Yeah I think they're mistakingly thinking that value types are passed by reference
Use this param type and nothing more
however the playerstat isnt
figure it out from that
all good
appreciate all the help
how would i go about implementing a compass to point in the direction of a gameobject? i thought it sounded simple but im realising i don't know what the most effective way to do it would be
can someone help me with my code i am getting this error: NullReferenceException: Object reference not set to an instance of an object
but i cant find anything wrong
here is the part that the error says its in:
private void Attack()
{
Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(attackPoint.position, attackRange, enemyLayers);
foreach (Collider2D enemy in hitEnemies)
{
enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
}
}
https://paste.ofcode.org/36mad2FcwkuU72qvdLtHxnN Hey all, I'm trying to make a timer that counts down (like an ability cd) that displays on the screen. My plan was to put the code in the game manager script, access it in my player controller script, assign it to an IEnumerator and call it when a Input key is used. It's the final method in this shared code that is giving me the issue. It wants me to pass a argument to the method and I don't want to because I can't do anything with it. If I swap out the variable "timeLeft" for the new argument, it doesn't work because I can't call that argument outside the method to display it on the screen (line 20 wouldn't be able to access it), I've tried thinking about rearranging the logic to be able to use an argument and I come up with nothing. I assume I'm going about the entire process wrong. Been sitting here for almost 2 hours and google hasn't helped, everything is adjacent to what I'm trying to do.
So I tried public void AbilityCooldown(float nothing)
{
if(timeLeft > nothing)
{
timeLeft -= Time.deltaTime;
phaseText.text = "Phase Cooldown " + timeLeft;
}
}
}
and set the argument to 0, it starts the countdown for a few milliseconds and then stops the countdown
Hey, guys! I want someone to explain me what's the difference between dynamic bool and static parameters?
On my inspector, I see dynamic bool and static parameters when I want to use a specific method from a class.
That's what I mean
you forgot to assign objects to your code. you've added the script but not told it what the variables are
lol
Take for example an Input Field. That has an On Value Changed event you can bind directly from the Inspector.
If you select from the Dynamic section, then you can use methods that accept a single string parameter. When the event is raised by the Input Field itself, the new value is passed to that method parameter and you can use it.
If you don't select Dynamic, then a field appears where you can provide a constant value to pass to the method, from the Inspector directly
I'm making a 2D shooter and I'm trying to get the triangle to follow my mouse, but it's following it from it's side? Can anyone help please. I want to the tip of the triangle to point towards my mouse
This is my code
transform.right = targetPosition - transform.position should work no?
On the needle. Although you have to remove the y
Hah, same solution twice
This?
yeah
You probably just need transform.right = dir where dir is the direction from the player to the mouse (world coords)
make sure the needle still matches when putting it in Local Pivot mode
Ahh, it's opposite in Local Pivot. How can I change it?#
make a proper empty gameobject and parent needle graphics as child. Rotate empty parent
I still have the same issue though, the needle isn't facing my mouse 😦
did you fix the line of code too and where did you put script ?
This is my code. Is there anything I should change?
And I got what you mean now. I should add my script to the Empty, not the needle
after is fixed yeah you can just do transform.right = dir
I'm not sure what you mean
How do I choose a random game object from the scene with the same tag
For example selecting a random enemy from the scene
put them in array and pick random index
Do you mean I add this to the bottom of my code?
No, it replaces a good part of it
All the trigonometry you have here (Atan2) is from a very popular tutorial and is far from the easiest and simplest solution
So, taking your last screenshot, it will replace lines 17 and 18
So, I should replace those lines with: transform.right = mousePos;
right?
I'd also avoid using "magic numbers" like 5.23f because as soon as you move the camera on Z, it'll break
No, you need to compute a direction vector from object position to mouse position
(mousePos - objectPos).normalized if you want to do it cleanly. Normalizing makes sure the length of the vector is equal to 1
Making it a direction vector
Can anyone help me tweak this correctly? When I call this method I'm expecting to see timeLeft decrement by 1 per second until it hits 0 (value I've passed to the nothing argument) but instead it just instantly jumps to a near zero decimal number instantly when called.
public void AbilityCooldown(float nothing)
{
while(timeLeft > nothing)
{
timeLeft -= Time.deltaTime;
phaseText.text = "Phase Cooldown " + timeLeft;
}
}
I don't understand how I can do that
I wrote the code, literally
You have to put the result into a variable, and use that
Okay
This might freeze your game if you pass the wrong value to this method!
Use a coroutine instead
I did, sorry let me paste both code using paste of code link
You don't need lines 14-15
This screws with the direction calculation
Basically it was the "long form" of creating a direction vector
Okay, I've removed lines 14-15, but I still get this weird movement when the mouse is on the left side of the player
Game Manager that has the method: https://paste.ofcode.org/VSCi6UUY6A8HyBRYydEVpb
Player Controller that uses the method: https://paste.ofcode.org/gm9aX6agysTU4XN3Fn3LF9
@short hazel this is how I've tried to implement it, this is my first day with these concepts so I'm sure its something simple and easily missed by me
That's physics. Your object is colliding with the ground and glitching out
Could you give me some guidance on how to do that please?
No your code is correct
But my gun doesn't have a collider attached to it and it also happens when the player is in mid air
As long as both objects are in the same space, the direction will be correct. I've done both in the past (all world, all screen, even all viewport) and they worked correctly
There's some position changes going on here then, it's not related to the code that rotates the object
Are you sure there's no collider, even on the child objects?
The gun is parented to an empty which is parented to the player. Only the player has a collider
Also, should my Z rotation value be changing when rotating the gun?
Only Z should be rotating
shouldn't you set the mousePos.z to 0? not 5?
if the direction calculated is Vector3, it will affect the cast to Vector2 after (if the direction is not actually in 2D space)
They are all rotating
If other axes change, then you've screwed up with the magic numbers and they're the ones making the calculation fail
Even with " mousePos.z = 0f " , the issue happens
Basically line 11 should be removed, and to be extremely safe dir.z should be set to 0 prior to feeding it to transform.right, so the vector is "flat on the screen"
Yesssss, it's working now!
Thank you so much everyone 🙂
Wait, spoke to soon
When I turn, the needle turns and the direction becomes inverted
So the back of the needle is facing my mouse instead of the front
How are you flipping the player when you need it to face left?
Setting the scale to -1 will cause that issue, because every child will also be flipped
ahh yeah, I'm setting the LocalScale to -1
yeah i prefer avoiding that, since it would be the player transform.right incorrect after
No it would be correct because nothing on the object has changed
Except for some display setting
Why isn't it letting me do this? I'm trying to rotate it 180
player would be facing left but the transform.right is still facing right
Yeah they want to aim the gun to the mouse independently of the player rotation
.rotation is quaternion only goes (0-1) never directly change those. also you cannot modify the single property like that
you would need to do transform.localRotation = quaternion.euler
Hey, what would be the best way to check if a new spawned room spawned in another room?
my room structure looks like this:
BiggerRoom
-> Floor
-> Floor 1
-> ...
-> Walls
-> ...
overlapbox
I'm confused as to what I do now
wdym
Oh wait, my bad. I was changing the Quaternion.Euler results and it was flipping the entire world
Thank you for the help it's working now! 🙂
took the script from the docs but each single part that build the room triggeres each other
Game Manager that has the method: https://paste.ofcode.org/VSCi6UUY6A8HyBRYydEVpb
Player Controller that uses the method: https://paste.ofcode.org/gm9aX6agysTU4XN3Fn3LF9
been stuck here for awhile now. I think what is happening is the Time.deltaTime isn't working maybe because it's outside the update method. The timer goes from 10 to near 0 instantly. Is anyone able to identify the problem? I'm using a coroutine but doesn't seem to help anything
are you trying to avoid spawning room in the same spot /
this does trigger the hit each second multiple times in console
How complex are these shapes? Could it be represented by a grid so you could just check if an index is null or not?
only basic so far, no real complex shapes. currently thinking about just doing box colliders on the prefabs but i dont know if thats good on long term
goal is to build a modular procedual dungeon generation. Done it with grids, now i want to try this out but i need a way to detect if they collide or spawn on the same spot
Any ideas why this is consistently returning false?
I've checked and the position is accurate and the layers are correct
I've tried and I'm out of ideas
I will try drawing a gizmo on it to verify 100% its not the position
Position is perfect
Strange, I've actually not tried CheckSphere, but perhaps trying SphereCast OverlapSphere* instead
otherwise I could only guess it's a collider issue if you're not defining a layer mask
Oh I fixed it, it was the way I added it to the editor GUI wasn't proprely translating the layer numbers
I just put it on a different script and grabbed a reference. Works fine
Hey, guys! How to set my current resolution to my default pc resolution on my game in Start()?
I am making now resolution settings and when I am entering the game I don't see my current resolution there and I see another resolution I have in my dropdown list.
I did something like that!
{
// Every variable or initialization that has to happen when the game starts in here!
Screen.SetResolution(currentResolution.width, currentResolution.height, Screen.fullScreen);
resolutions = Screen.resolutions;
filteredResolutions = new List<Resolution>();
resolutionDropdown.ClearOptions();
currentRefreshRate = Screen.currentResolution.refreshRate;
for (int i = 0; i <resolutions.Length; i++)
{
if (resolutions[i].refreshRate == currentRefreshRate)
{
filteredResolutions.Add(resolutions[i]);
}
}
List<string> options = new List<string>();
for (int i = 0; i < filteredResolutions.Count; i++)
{
string resolutionOption = filteredResolutions[i].width + "x" + filteredResolutions[i].height + " " + filteredResolutions[i].refreshRate + "Hz";
options.Add(resolutionOption);
if (filteredResolutions[i].width == Screen.width & filteredResolutions[i].height == Screen.height)
{
currentResolutionIndex = i;
}
}
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
I have also an error here
UnityException: get_currentResolution is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), call it in Awake or Start instead. Called from MonoBehaviour 'SettingsManager'
it says how to fix
you have to call it from inside a function
Yeah!
@rich adder What can you say about my issue with resolution?
I have to set my current resolution when entering the game so in start() I have to do something.
What I did was that check it out:
Screen.SetResolution(currentResolution.width, currentResolution.height, Screen.fullScreen);
That's what I did in start method like you see in the code above
whats the issue
I fixed it right now anyway I just had to set my screen current resolution in start method like I did in code and that's all for one reason I had that error because I declare that Resolution currentResolution = Screen.currentResolution before Start method.
yeah thats what error saying you cant run method while declaring var
Vector3 pos = new Vector3(370,-25-(history.Count * 50),0);
Debug.Log(pos);
GameObject prf = Instantiate(messagePrf, Vector3.zero, Quaternion.identity, contentTransform.transform);
prf.GetComponent<TextMeshProUGUI>().text = message;
prf.transform.localPosition = pos;
contentTransform.sizeDelta = new Vector2(contentTransform.sizeDelta.x, contentTransform.sizeDelta.y + 50);
prf.GetComponent<TextMeshProUGUI>().color = color ?? Color.black;
history.Add(content);``` this is the code for an chat but the messages arent on the right coordinates first one is right on -25 but the second is on -125 but in the console it prints the right coordinates
Or a Vertical Layout Group so it does the placement for you
thank you that worked
Hi all, I've been following the Cloning WoW series on youtube (from 4 years ago so I can't get support there unfortunately) - and I'm at the stage where I'm trying to control character movement but I'm having some issues - is there somewhere I can get help on this? also willing to pay for the solution
You can ask here as long as it's about code, provide enough info, and follow the recommendations in #854851968446365696
Paid work might fall into the collab section and must be posted on the Forums instead
!collab
We do not accept job or collab posts on discord.
Please use the forums:
• Commercial Job Seeking
• Commercial Job Offering
• Non Commercial Collaboration
If I have
Level : SciptableObject
and
ExtendedLevel : Level
Is there a easy way to (cast a level / create a new extendedlevel using a level) into an extendedlevel in a way where i don't have to manually re-assign all it's values?
you don't need to reassign values when you extend
I have set up the camera controller so that when i hold left click it 'free looks' around the character - this is working at the correct speeds, but I also have it that when i hold right click it controls the character rotation with the camera - but the PAN (y) for this is moving at a very slow speed (the tilt x is corrcet speed)
Is this bad?
private void OnTriggerStay(Collider other)
{
if (other.CompareTag("Player") || other.CompareTag("NPC")) {
if (other.TryGetComponent<Traits>(out Traits traits)) {
RuntimeAttributeData energy = traits.RuntimeAttributes.Get(CharacterAttributes.energy);
if (energy.Value <= energy.MaxValue) energy.Value += 0.1f;
}
}
}
Do I need to cache TryGetComponent?
Do you specifically needs the tags
Probably not if I only check for component
right, the components themselves can serve to identify group types and behaviors
usually more of a job for interfaces
Please let me know what else I should add above to get an answer to my problem ^
Is there a more performant way than TryGetComponent then?
That's fine, just make sure the collider object itself limited with components for identity purposes
because basically you do a linear search (I think it's through reflection) through all components on the gameobject
I reckon you could use OnTriggerEnter/Exit instead, check the tags and component stuff in the enter method and cache to a collection if it passes those checks. Then OnExit you try getting the component from the collider that exited, then if it passes remove it from the collection
Keep the tag checking, it's more efficient than checking the component everytime (if you have lots of types with collider to check)
This is assuming the operation is frequent and you have profiled it and found a bottleneck in performance
I did use OnTriggerEnter initially and npc.StartSleep() and when it was 100 I made it move out of the collider
the problem with tag checking is if you have more than a handful of tags
but for what you have there it is probably the quickiest solution if we care about micro performance
Does the component order in the inspector matter?
Will it hit the transform first?
it checks for the collider bounds not the transform
TryGetComponent ?
huh?
He said it's a linear search
So if I have 1000 components that would take longer I presume
if you've 1000 of them, cache it when you spawned them for the 1st time
im not sure if the ordering on the inspector matters, but it'll search through all components until a component is found
something to test but I wouldnt bet on it
The order of that could change if unity wants to change it, so best not to rely on it ever
the order is guaranteed for GetComponents with what you see in inspector
the unordered one is the GetComponentsInChildren
if they made the tag system a bitwise enum much like layer masks I'd probably use it
why?
1 operation to check against
yeah but if you're searching if(playertag), if(enemytag)
Hey, so I got this problem where I have tryed to use a function called AddForce from the rigidbody2d class to add a force when the player suddently changes direction. However, it is not working at all, as if it isin't even there. I have used debug.log to check if maybe the if statment that it is in is not working properly, however, the logic works perfectly fine. I have no idea how to fix this and I need help. Here is the part of the code where I am having an issue with:
{
if(Input.GetKeyUp(KeyCode.A) == true && Input.GetKey(KeyCode.D) == true && rb.velocityX > walkingSpeed)
{
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(rightDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
}
else if (Input.GetKeyUp(KeyCode.D) == true && Input.GetKey(KeyCode.A) == true && -rb.velocityX > walkingSpeed)
{
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
}
}```
and here is my whole code
So you're saying it never executes the stuff inside the if loops or?
no the if statment works fine, it is these two lines of code that is not doing what the're supposed to do
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(rightDirection * forceForSuddentChangeOfDirection, rb.velocity.y));```
and this
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
Have you debugged "forceForSuddenChangeOfDirection" to see if it's other than 0?
Copy that fast before it'll get deleted for being too long !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.
do you mean debugging the function to see if it is working? If it is that then yes along with the if statments by adding the debug.log method. It works as intended.
I want to Instantiate an object from a prefab that is in my Assets folder. How do I reference this object without connecting it to the script via a public GameObject variable?
https://paste.ofcode.org/rttykLcch2sYqT62ALEGN2
Hello everyone this code fora dialogue script im using and i wanna ask 2 questions:
1-How do i make that audio starts playing when the dialogue starts and stops playing when all dialogue is done
2- how do i make it that the next line starts immediatly after the first one is done instead of having to press "N" in this example
Learn about the Resources folder
Resources.Load
{
Vector3 directionToTarget = targetPoint.position - transform.position;
float distanceToTarget = Vector3.Distance(targetPoint.position, transform.position);
if (distanceToTarget < maxDistance)
{
float forceFactor = forceStrength / rb.mass;
rb.velocity = directionToTarget * forceFactor;
}
else
StopDrag();
}```
I would like to use AddForce instead of directly changing the velocity, but I don't know how to do it while still having a similiar snappy movement.
Any recommendations?
I have a component that I need to have default values when I create the object. Do I need to prefab the entire object with the component to save them? What if I have two components with different values and want to decide what to attach to the object? I need to instantiate a prefab as a child?
In your script when you state the variables use "private int varA = //Set your default value"
Just use a equal sign.
I want to tune the values in the editor
Set a target velocity and change how powerful the addforce is compared to how your moving relative to the target velocity.
dictionaries are mutable but this value is read only for some reason?
im new to dictionaries so i probably am missing something silly
How can I perform an action the moment the screen gets touched and only then. I have been trying for 2 hours straight at this point to make it work and I cant. Originally I used the old input system and I had this:
Touch touch = Input.GetTouch(0);
if(touch.phase == TouchPhase.Began)
{
planetToFall = Instantiate(currentPlanet, Spawner.transform);
}
and then I changed to the new one and wrote this, and Unity keeps crashing everytime I touch the screen
UnityEngine.InputSystem.TouchPhase phase = touchPressAction.ReadValue<UnityEngine.InputSystem.TouchPhase>();
if(phase == UnityEngine.InputSystem.TouchPhase.Began)
{
planetToFall = Instantiate(currentPlanet, Spawner.transform);
}
the problem in both cases is that Instantate() runs everyframe instead of one which is not what i want
If you didn't when you state dictionaries you need to have a = new dictionary after the variable.
perhaps flag it after you enter the statement and unflag it if state is not Began anymore
I'm trying to make an inventory hotbar where the player presses one of the number keys to equip a certain item that they own. When I press the button, however, some of my models are off-center. Is there any easy way to fix this without having to fix some aspects of the model in blender?
I instantiate my models like this:
Instantiate(item.model, itemSpawn);
the local variable created in a foreach loop is a copy because KeyValuePair is a struct. iterate over a list of the keys and modify the values using the keys isntead
Have you checked the instantiated object to see if it has a local position of zero?
Is there a way to map strings to scriptableobjects in the inspector? Since you can't use a dictionary
If it does have a local pos of zero and it is not where you want it to be, you can parent it to another game object which will work as the center point of that model, then reposition the now child model object to wherever you want
Why'd you want to do this? String IDs?
make structs
@wild cargoI have scriptable objects in the project and need to create components from them: Traits.SetTraitsWithClass(npc, <scriptableobject>);
!code
there are already semicolons
📃 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.
my apologies
like this? what does .Values actually do I couldnt find it in the docs (I didnt look very hard to be fair)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
public float speed = 5f;
public float mouseSensitivity = 2f;
public float jumpForce = 5f;
private Camera playerCamera;
private CharacterController characterController;
private float verticalRotation = 0f;
private float verticalVelocity = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
playerCamera = GetComponentInChildren<Camera>();
characterController = GetComponent<CharacterController>();
}
void Update()
{
// Player movement
float horizontalMovement = Input.GetAxis("Horizontal");
float verticalMovement = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(horizontalMovement, 0f, verticalMovement);
movement = transform.TransformDirection(movement);
movement = speed;
// Jumping
if (characterController.isGrounded)
{
verticalVelocity = -0.5f;
if (Input.GetButtonDown("Jump"))
{
verticalVelocity = jumpForce;
}
}
// Gravity
verticalVelocity += Physics.gravity.y Time.deltaTime;
movement.y = verticalVelocity;
// Mouse look
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
float mouseY = -Input.GetAxis("Mouse Y") * mouseSensitivity;
verticalRotation += mouseY;
verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);
playerCamera.transform.localRotation = Quaternion.Euler(verticalRotation, 0f, 0f);
transform.rotation = Quaternion.Euler(0f, mouseX, 0f);
// Apply movement
characterController.Move(movement Time.deltaTime);
}
}
there are already semicolons, but the error is there
As Mao said, you should make structs for holding both the scriptable object and the string, then at runtime map it to a dictionary
If your IDE is not underlining errors in red you need to configure it !ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
is there a way to automatically size a boxcollider around my gameobject ?
You can lazily map them using a property, so like
[Serializable]
public struct MyMappingStruct
{
public string myString;
public MySO mySO;
}
private Dictionary<string, MySO> _soMappings;
[SerializeField] MyMappingStruct[] _mappings;
private Dictionary<string, MySO> SOMappings {
get
{
_soMappings ??= _mappings.ToDictionary(m => m.myString, m => m.mySO); // ??= is essentially just "if (someValue != null) then assign it to this value"
return _soMappings
}
}
This should give you an idea of the implementation
@wild cargoStruct doesnt show up in the inspector
Use [System.Serializable]
I tried both of these and the model is still in the wrong position (the same thing keeps happening). I think this is because of the model's pivot point. What else can I do?
[System.Serializable]
public struct CharacterClasses {
public ScriptableObject peasant;
public ScriptableObject knight;
}
There's no way this approach can fail, have you changed the instantiation target to be the new parent you just made?
That does not serialize? It's because you cannot use the default ScriptableObject because what fields would show up? Nothing because there is none in the base (abstract?) implementation
I dont udnerstand this error. I made a copy of the list before iterating on it. I still keep getting this error though. Not sure how thats possible.
Okay got it
That is not a copy of the dictionary, it is a copy of the dictionary's reference
That's not a copy, that's another variable pointing at the same data
oh, how would I fix the error then?
I would attempt to use LINQ's myCommands.ToDictionary() to do a soft copy first
the target is this empty
I need more context
Like what are the close children/parents of that object?
Store the keys of the dictionary in a list using .Keys. This will be a copy, and you can loop over that safely and use that key to modify the dictionary.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys?view=net-8.0
Here's the full situation:
This is my code:
void equip(ItemData item)
{
if (inventory.Contains(item))
{
int childCount = itemSpawn.childCount;
if (childCount > 0)
{
for (int i = 0; i < childCount; i++)
{
Destroy(itemSpawn.GetChild(i).gameObject);
}
}
GameObject newItem = Instantiate(item.model, itemSpawn);
newItem.transform.localPosition = new Vector3(0, 0, 0);
}
}
itemSpawn is set to the "Item Spawn" object in the hierarchy below. The object that I'm spawning is a model imported directly from blender as a .fbx file.
I am having a weird tilemap instantiation offset problem. I am spawning a chunk of tilemap that is 20 by 20 at vector3.zero and in the inspector, both the grid and the chunk are correctly showing 0,0 for their positions. However, the actual center of the chunk is actually at 1, -1, and the borders start at -9 and go to 11 for the x axis (left to right), and -11, 9 for the y axis (bottom to top). So it seems even though the grid and the tilemap are at position 0,0, they are off by 1, -1 somehow. Anyone have any ideas?
There has to be an easy way to do this. What is it, where should I look?
up here ⏫
I don't think the hierarchy of the instantiation parent matters all that much, what does the prefab's (model's) hierarchy look like?
@wild cargoActually dont need to use string, can I get a reference to "ScriptableObject peasant" from the array looking up by type instead of looping through it?
It's a bit unintuitive, but in order to loop over the children of an object, you can just do:
foreach(Transform child in someObject.transform)
A transform is secretly also a list as far as C# is concerned
it's just an imported model
Then if you want a custom center point without messing with the pivot in blender, you should make another prefab and nest that model seen in the image into it. This way that new prefab's root object is not the model, and instead the center point of it, so you can move the child (model) freely until the center relative to the model is where you want it to be
I am starting to suspect the easy way of "fixing" this is to offset my grid by 1, -1 and calling it a day
I didn't know that. By doing that child is a Transform of each child game object I am iterating on?
Yeah because in "Transform child" the Transform indicates the type of each iteration's "child", which in this case is Transform
Also for anyone interested, it prolly gets the list of children by implicitly converting into a list of all children in it when a collection of transforms is expected
thanks! that error was driving me up a wall.
Transform just implements IEnumerable
That's why it works in a foreach
Yep. You can consider it working as if there were a function transform.GetListOfChildren() except the GetListOfChildren() is silent. It works like an ordinary foreach using some dark wizardry behind the scenes (Transform actually being an IEnumerable)
I always found that so strange.
some type of transform.children property or transform.GetChildren method would be much cleaner
there's likely some reason for this
Thanks! It worked. How would I make this collideable, though? Like, a rigidbody that can move and stuff.
Yeah, I see this piece of code and it seems it's calling GetChild() with an increasing index
[Serializable]
public struct CharacterClass
{
public static ScriptableObject peasant;
public static ScriptableObject knight;
}
[SerializeField]
CharacterClass[] _characterClasses;
How do I get the reference for peasant in this array?
Something like this but correct syntax:
ScriptableObject so = Array.FindIndex(_characterClasses, c => c == CharacterClass.peasant);
I have a model which is an empty with of the actual visible parts of the model parented to it (an empty with many meshes). I want to make this model act like a rigidbody, but how do I do this? Adding a rigidbody to the empty just makes it fall through the floor.
It depends which one you want. The array contains multiple "CharacterClass"s
but generally you get an individual one from the array with an index. e.g.
CharacterClass cc = _characterClasses[5];```
From there you can do whatever you want with it:
```cs
ScriptableObject peasant = cc.peasant;```
I will note a few concerning things here though:
- Your class name should not end with
Class. We already know it's a class, that's just noise for the brain. - Your fields are
staticwhich means they're not actually associated with any particular instance of the CharacterClass struct. This means my example above won;'t work but it's also pretty nonsensical for this to be static, though to be honest I don't really understand what you're trying to accomplish with these fields
Class is a reference to the ingame class, not C# class
- Why are you using
ScriptableObjectas your reference type for those variables instead of your actual ScriptableObject derived class?
But I dont want to find by hard index, instead lookup by type
then you want a Dictionary, not an array
Yeah but inspector doesn't work with dictionary
You can put them in the inspector with an array and then populate a dictionary from the array at runtime in Awake
to get the best of both worlds
REgardless I have no idea what's going on with this:
[Serializable]
public struct CharacterClass
{
public static ScriptableObject peasant;
public static ScriptableObject knight;
}```
Why have a struct with nothing except a couple of static fields?
The struct is useless at that point since it holds no data
it certainly isn't serializable!
To populate in the inspector
Is there a way to make a clone of a key, so I can have multiple of (technically the same key) in a dictionary. I know its hacky but It would instantly solve my problem. Like im adding 2 of the same CommandSO into the dictionary here and Is there a way via code like in my else statement?
but there's no data in the struct so there's nothing to populate
the static fields don't count
A Dictionary cannot have duplicate keys
If you want multiple things in the dictionary for a single key, make it a Dictionary<KeyType, List<ValueType>>
Or use a different key that's unique
can someone help me with this please
what is rb.velocityX 🤔 that's not a thing. Did you retype this?
rb is a refrence to the rigidbody2d
Yeah I got that part
velocityX is not a property that exists on Rigidbody2D
this should be a compile error
really? I have been using it and it gives me the value of the x velocity
show a screenshot of your IDE when you mouse over that
I would expect rb.velocity.x
@wintry quarrySo essentially I am forced to do it like this?
[Serializable]
public struct CharacterClass
{
public ScriptableObject peasant;
public ScriptableObject knight;
}
[SerializeField]
CharacterClass[] _characterClasses;
...
CharacterClass cc = new();
NPCManager.Instance.CreateNPC(cc.peasant);
...
Convert to a dictionary, lookup to get ScriptableObject
yea or that
I don't really understand what you're trying to do
Again why are you using ScriptableObject fields?
nor do I understand this code snippet really.
Because the assets are SOs
but they're not raw SOs
they're some subclass of ScriptableObject
so what could be the problem?
so why would you use ScriptableObject instead of the actual concrete type
you'd have to show the rest of your code. If you are setting the velocity directly elsewhere, it will overwrite any forces you add here
Please share it in a paste site
not uploading in discord
but I already sent it here#💻┃code-beginner message
wait sorry
here
@wintry quarry
ok so I have a bunch of tilemap "chunks" which are just sets of 20 by 20 tiles. in prefab mode, it seems like their center point is just... all over the place. what controls what the "center" of a tilemap or prefab is? they are both set to 0,0,0 in terms of position and 1,1,1 for scale (default) and are the same size (20 by 20 tiles)
As you can see they are really simple tilemap prefabs but the pivot point is just all over the place
it means that when I spawn random chunks at -20,-20 to 20,20 it's genuinely just hilarious, these chunks really think they are on some sort of grid somehow
You need to switch this to Pivot
(by pressing Z or from this menu)
then you will see the actual position of your objects
that is, I believe, only for moving things around in the scene menu
It's for controlling where the tool handle appears
If you want it to appear at the object's actual pivot/position you set it to Pivot
If you want it to appear at the average of the bounds of all the renderers in the subhierarchy, you put it on Center
I re-ran the program with it set to center and as you can see, the origin of the instantiated tilemap chunks is still using its pivot rather than its center.
tthe program is not affected by that
your code will always use the object's pivot
assuming you're talkking about transform.position
Ah, let me rephrase, then.... I would love it if the pivot of my prefabs was reset to the center of the prefab. is there a way to set the pivot point to match the center?
By setting it to pivot you can see the object's actual pivot and this will let you better think about things when writing your code
depends what the prefab is made of
it's just a tilemap, I posted the full hierarchy/inspector above, it's just 20x20 tiles
in genral you can always add an empty parent object / move the renderer down to a child object. Then move the child object as desired to get it so the parent's pivot is where you want
for a tilemap you would actually repaint tiles
if you want to "change the pivot" for it
otherwise use the workaround with the empty parent
each chunk I've saved out has a different and very silly pivot point that, now that I think about it, might actually be the coordinates of the last painted sprite I've painted in that chunk
Yeah it's basically due to how you created your prefabs
you weren't careful about the coordinates you were painting
so you painted different coordinate ranges on each
Ah, I see, so you're saying the relative coordinates of the sub-tilemap within the prefab controls the pivot?
Just open one of your prefabs (with tool handle in Pivot mode)
and look at where the tiles are inside the prefab relative to the location of the root prefab object
that's your issue
fix all the prefabs so they are at the same position relative to the prefab root
there is only one object - the prefab itself - and it's only got one component - the tilemap. I see what you're getting at, though. I should adjust the tiles within the simulated "grid" so that they start at -10 and end at 10 in both directions and problem solved, since the pivot location is inherited from 0,0 within that sub grid I was painting on. funky stuff!
that's quite strange. I suppose I had assumed the relative-to-the-sub-grid location was discarded in favor of the relative-to-the-real-grid location
ah well, as long as it works 😛
thanks!
what's the "real" grid exactly?
the grid that I am instantiating the tilemaps onto at runtime
Doesn't each tilemap have its own Grid?
look at this, you've saved my project! what a hero! 😛
No, it's one grid, and then the tilemaps go onto it.
I have no idea if this is performant or not but it seemed like the proper way to structure this sort of generation?
But what components on are on those spawned clones? Just Tilemap?
just tilemap
interesting. Never tried it that way
well and a tilemap renderer
Yeah not sure how that interacts with a parent Grid. I guess it doesn't interact at all?
I'm kind of winging it lol, I've done a ton of 3d procedural generation but never 2d. I think the parent grid still controls them the same way that a regularly drawn grid and tilemap works
I assume I am going to have to start culling the tiles eventually for perf reasons but I'm not sure when that "eventually" is
How can I create an instance of a referenced scriptableobject in the inspector?
Since they're each using their own TIlemap Renderer I assume Unity's frustum culling will kick in automatically
Instantiate will create a copy of anything that derives from UnityEngine.Object, including your SO
Well, I give up for today
giving up is not allowed
hello, i’m new to programming, anyone would like to connect with me? i just need some people to talk with
hi, i started learning unity and the pathways on the site doesn't feel to be helping, what should i do?
why is not helping?
it s just like showing you a concept game to make
not showing all the functions and classes that u can use
those are in the documentation
yeah, it may help u a little bit
you have to learn how to read the docs
practice more code if you want to learn code
ty
📃 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.
The raycast isnt working for whatever reason? I checked the Z positions theyre both zero. The layer mask parameter is set to bomb in the inspector and the Bomb Gameobject is set to the Bomb layer
Try drawing it in the scene with Debug.DrawRay (passing a duration); I can't see anything particularly wrong with it
I'd also note that this snake-case naming convention isn't standard in C#
This worked i completely forgot about gizmos / DrawRay
The raycast was above the bomb hence why it wasnt working
is there a bool that gets checked when unity is about to destroy everything (for when quitting game/playmode or switching scene)?
For closing the game/play mode, you could use https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnApplicationQuit.html. Take a look at the notes towards the bottom depending on the platform you are building to. The closest thing you can do for the second one is to subscribe to the change scene loading events (very bottom of this page https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.html)
Rigidbodies rely on colliders for collisions, not the mesh renderer. Just add a collider to your character and the floor and it should prevent it from falling through
lemme lemme try
havent seen you since like before haloween though, people do carve you huh
yeah I took a break for awhile 😅, had a bunch of class work to do
Nice name
so, i have a static file (not inheriting from monobehaviour), and in one of the static functions in it, i want to create a short delay in execution. how can this be achieved?
is having an object with monobehaviour necessary to do this
ultimately you'll need something to orchestrate this delay. A static function on its own cannot have a delay in it directly
look into coroutines or async functions
I guess maybe async can work without a MonoBehaviour? I'm not that familiar with how async works in Unity
One of async's benefits and downsides is that it's disconnected from Unity's object lifetime
So if you don't want async functions to leak out of scenes or into edit mode you should use a MonoBehaviour's destroyCancellationToken
On coroutines however: You can start coroutines in any class as long as you use StartCoroutine from a MonoBehaviour to tie it to its scheduler
hmm okay that helps
This is the first time I have written shader code. I am following this tutorial to help wrap my head around it all.
Traditionally, the code on the right of the screenshot was written in a .shader file I believe, however I am using Shader Graph in 2022.3.15f1 and can't seem to find a way to edit the custom function node through a text editor in Unity.
Can anyone help me figure out how I can follow this tutorial and write the shader code?
can the same coroutine have two instances of it run parallely (with different parameters)?
you can read and set the member data of the object instance, but I'm not sure about the execution ordering. Probably related to when you start them.
i just need to make sure both will execute eventually, a frame or two of time delay is irrelevant in my case
there's no parallel processing with coroutines, they run through the same update cycle as the rest of your code
ah, okay
you can think of them as a standalone mono scripts without the overhead
and the benefit of sleeping them since polling in update is not always warranted when you want to check every 5 seconds or so
Unity has starter assets you can use . . .
yes just StartCoroutine twice and provide whatever params you need, both will run
Gone back to Unity after a long time for a job and got this error in a old project, in my array. Looking the docs, RemoveAt is still a thing, shouldn't this work?
where is the docu?
Arrays are fixed size, it has never been a thing. Are you looking at List docs?
I think this is the more relevant part:
Note: This is javascript only. C# does not use this feature.
Now that you mentioned yeah I don't remember it being a thing
I gotta ask the me from four years ago what I was doing 
there is no such thing in 2023 (2024?) so you need to change it
If you need to change the collection size at runtime then use List instead
(which does have .RemoveAt)
Thank you guys!
i dont understand most of this code, its a third person camera that orbits the player but it doesnt stay behind the player when the player turns, ive been trying to google for a hour and cant figure how to do it
public class ThirdPersonCamera : MonoBehaviour
{
public Transform playerTransform; // The playerTransform object to orbit
public float mouseSensitivity = 150f;
float yRotation = 0f;
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
yRotation -= mouseY;
yRotation = Mathf.Clamp(yRotation, -10f, 60f); // Limit vertical rotation to avoid flipping
// Orbit around the playerTransform
Quaternion rotation = Quaternion.Euler(yRotation, 0, 0); // Only rotate around Y and Z axes
Vector3 negDistance = new Vector3(0.0f, 0.0f, -5.0f); // Adjust the distance from the playerTransform
Vector3 position = rotation * negDistance + playerTransform.position;
transform.rotation = rotation;
transform.position = position;
}
}```
whats the camera parented to?
a capsule which is parented to a player, the player is what rotates left and right
yeah that bad setup, that makes the camera rotate along the player as the player rotates, am i right?
it does, but not here cause the code overwrites it
I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random
could someone help me debug this problem, ive been on it for a while but dont see whats wrong with it.
I have an inventory system but the first slot keeps getting overriden because it thinks the slot is null or empty.
heres my inventorymanager function:
public void AddItemToInventory(GameObject pickedUpObject)
{
// Check if the item to add is not null
if (pickedUpObject != null)
{
// Get the Item component from the picked-up object
Item itemToAdd = pickedUpObject.GetComponent<Item>();
// Check if the itemToAdd is valid
if (itemToAdd != null)
{
// Iterate through the inventory slots to find the first empty slot
for (int i = 0; i < inventorySlots.Count; i++)
{
InventorySlot slot = inventorySlots[i];
// Check if the slot is empty
if (slot.IsEmpty())
{
// Log the slot index where the item is added
Debug.Log("Added item to slot " + i);
// Add the item to the empty slot
slot.AddItem(itemToAdd);
// Update the UI to reflect the changes
slot.UpdateUI();
// Item added successfully, so return
return;
}
}
// If no empty slots are found, handle as needed (e.g., show a message)
Debug.Log("Inventory is full or no matching slots.");
}
else
{
Debug.Log("Picked up object is not an item.");
}
}
}
heres my other functions:
private Item currentItem; // The item currently stored in this slot
public bool IsEmpty()
{
return currentItem == null;
}
I've already checked and the slots are seperated into their own boxes so its not like theres only 1 slot to go into, the index is telling me its only trying to enter the first box, and considering the first slot image keeps getting overriden, it tells me that the IsEmpty function is not working how it should
Guys how do I make Time.deltaTime useable with an int value instead of a float? I can see some solutions like using Math.FloortoInt but even in unity documentation there isn't a great example of how to implement it (do I instantiate a variable with Time.deltaTime?, am I forcing the float number to convert to a int in start method? etc). Here's the code in question: https://paste.ofcode.org/YGpTJHkHZK6sCRJiRRg4gu
code block in question starts at line 59. Any insight would be much appreciated
Mathf.(Floor)ToInt() will "floor" (so 6.83 => 6 etc.) the given float value to an integer, so you just put the float value in the function's params and it outputs an int using that formula
No sorry, your timeLeft variable is actually an integer, which means when you subtract Time.deltaTime from it at runtime it'll lead to a compile error
timeLeft is a private float
oh I didn't remove the code I was playing with, mb
yes it throws an error, I was just trying to figure out where to/what to change to int, timeLeft or Time.deltaTime
But rhen why even convert 10.0f into an integer at start when you can just make it the default value in the definition, so
private float timeLeft = 10f
I don't want it as a float, because I get a compilation error. If it remains a float, the timer shows like millionths of seconds on the UI and I don't want that
compilation error as int I mean
That can be fixed easily by rounding it into whatever decimal place in the UI script you want
The actual value should be kept as a float
ah
If you just want it to show as an int in the UI just do this: ```cs
phaseText.text = $"Phase Cooldown {timeLeft:0}"; // the :0 tells it to display as a whole number, you can also do 0.0 for one decimal or 0.# to only show the decimal when there is one
Also, it seems like the bool "spaceCooldown" is never set to false, so line 59's if statement always runs, the else never does
This and also {timeLeft:n0} for regional formatting, if needed
it is, I just left out the bottom half of the code to try to cut back on the reading others had to do (didn't figure it had anything to do with my question)
Oh alr
is it better practice here to just paste the whole code regardless?
I'd just comment the 100 liner out to pseudo code and write what it does rather than copy paste it all
I'm checking this now thanks, and then I have some more research to do to understand it 🙂
I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random
that worked, thanks a ton. Also @wild cargo t thank you for the additional insight
Hi guys.
I am trying to build a map editor for my game.
I have a 8x8x8 grid, and i'd like to let the user create a cube by moveing the mouse and right click.
I am currently using a Raycast from mouse position, then taking the last raycasted item and create the cube at that position, but that's not what exactly i wanted because if the user wants to spawn a cube on the middle of the grid, this would be impossible because this will never be the last raycasted object.
Do you have any idea on how i can achieve this result?
I'm sure there would be a better way, but off the top of my head I guess you could do a distance check on the selected 'block' and maybe have the player use the mouse wheel or something to zoom in until the required block is at the same distance as the distance check?
raycast can hit multiple objects and you should introduce some ways so that users can select the exactly position as above comment
Thank you for your answer!
it may be a solution, but i don't like much the idea of using mulitple actions, it should be kinda fast to draw some cubes so i'd avoid the possibility of scrolling the wheel or pressing a button after moved the mouse and clicked if possible
Aye, is there any way for mixing let's say the raycast result and the mouse position to get the correct one?
the ray is created by mouse pos so i dont know how you mix them together, or you have already "mixed" them together
i have not mixed them, it was an idea but i don't know if that makes sense.
I thought the raycast is giving me all the slots aligned with the camera and the mouse, so i may take the mouse world position and find the slot that has the same coord inside the raycasted list, does that make any sense?
Is your scene 'static' or can the player move the camera around the grid?
you can move, zoom and rotate
the set of mouse pos in world space (yes "set of", not only a single point) is represented by the ray already
Okay, well if you're already zooming, my idea would work, you just need to set a 'desired' distance from the camera for the ray to hit (I think), you've got most of what you need already.
isn't the raycast ignoring the Z axis since i get all the slots looking forward from the camera?
yeah it would work, and i may go with that, i am just looking if there is a faster way for the user to draw the map instead of scrolling the wheel for every block, let's say an "automatic Z based on position"
bit of pseudo....
If 'slot' != distance { ignore slot}; type of thing
This is more of a design question than implementation. How exactly do you want the user to select the desired position?
again the ray can hit multiple objects including the object with larger z
so you must create other mechanisms to choose the exaclty block
ray doesnt ignore any z, but you let the ray ignore it
Are you giving the player any feeback on which block is selected? (ie, hologram type block that appears)
I have this 8x8x8 grid that will be invisible on the future.
The user is able to move, rotate and zoom on the grid, basically just like you make on the unity Scene.
I wanted the user to be able to create a Block in the air, so 100% free and not forcing him to create block on top of other blocks just to create a cube in the middle of the grid
Yup, hologram
i think you dont understand why a mouse position on screen can generate a set of position in world (the ray)
https://en.wikipedia.org/wiki/Ray_tracing_(graphics)
In 3-D computer graphics, ray tracing is a technique for modeling light transport for use in a wide variety of rendering algorithms for generating digital images.
On a spectrum of computational cost and visual fidelity, ray tracing-based rendering techniques, such as ray casting, recursive ray tracing, distribution ray tracing, photon mapping an...
That doesn't make much sense. So you'd prefer the block to be placed exactly in the middle of the grid?
For reference, unity would usually place object on surface of other objects that you drag on to.
if (Input.GetKey("1"))
{
calibration = 1;
}
if (Input.GetKey("2"))
{
calibration = 2;
}
if (Input.GetKey("3"))
{
calibration = 3;
}
if (Input.GetKey("4"))
{
calibration = 4;
}
if (Input.GetKey("5"))
{
calibration = 5;
}
if (Input.GetKey("6"))
{
calibration = 6;
}
how should i optimise this? i see its very unoptimised but i can't figure out an effective way to optimise it
That's the challenge, curently i am always drawing the cube on the last raycasted position on the grid, but this would not work if the user wants to put a block on the center of the map, because this will never be the last item unless you have filled all the layres behind
array of keycodes
loop unrolling is already optimized
if you prefer flexible way to write this, use loop
yeah but how
That's the question: how does the user decide where to place the block? How do you want to let them decide where to place the block?
how would i do that
*at what depth.
If I'm understanding correctly, this is the kinda thing you want to do?
array, for loop, if == ,calibration = index
when the user moves the mouse on the grid an hologram of the block is placed on the position from the mouse position (the issue is here, can't find the best way to get the right block), when the user sees the correct block, then it right click and it creates the block
yes that's it
yeah i got that part but i don't know the best way to go about it
exactly how I wrote ir, try to write the code then come back
But how would you adjust the depth of the selected block..?
yes, you dont understand mouse position to world position is one to many mapping
so you cant basically just use mouse position to get the block
That's the issue he's having if I understand correctly.
that's the question, i am not sure if there is a clever way for doing this
alright i'll give it my best lmao
My suggestion was to introduce a distance check of some kind as the player can already zoom into the grid and rotate around it. Can't think of another way.
TheMightySpud answer is correct, using the wheel or numbers to let the user select the Z layer block, but i'd like to know if there something more automatic to get that
Ok, well that's a design question then. There are many ways to go about it. One is allow the user to scroll the depth of the selection. Another one is just to place at the first hit cell. Another one is to select the farthest overlapping cell. Many ways and it all depends on your design idea.
It would need to be a distance to camera check though I Think as the raycast hit distance would change based on xy position of the mouse.
i've immediately run into an issue, how do i make an array of inputs? there is, to my knowledge, no variable type for inputs @languid spire
no need, I said an array of keycodes
Automatic in what way? The computer can't read the thought of the user. Unless you use some kind of neural interface.
what like [1, 2, 3, 4, 5, 6]?
i have said mouse position to world position will generate a ray and IMPOSSIBLE to just use the ray to get one position. sigh
no, KeyCode.1 etc
ahh, but whats the variable type for that?
KeyCode
KeyCode is the variable type.
ohhhhhhhh
!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 didn't know that! thats useful
[Header("Keybind Assignements")]
[SerializeField] KeyCode forwardKey = KeyCode.W;
[SerializeField] KeyCode backwardsKey = KeyCode.S;
[SerializeField] KeyCode strafeLeftKey = KeyCode.A;
[SerializeField] KeyCode strafeRightKey = KeyCode.D;
[SerializeField] KeyCode sprintKey = KeyCode.LeftShift;
Not an array (yet)
Maybe check if there are any blocks in vicinity and place at the closest cell to them..?🤷♂️
yeah, the solution i went for the first time was the first raycasted, but this would draw only the first layer cells, then i moved on the last raycasted and its much better since it always draw on the back, and if i raycast at the bottom of the first layer it gets he first layer since there is nothing behind, but the problem is to raycast something on the middle
What's the "something" in the middle? Is it fine to say select cell 4, 4, 4 in a 8x8x8 grid? Is that what you want?
yes
Then maybe avoid raycasts at all? Just use some math
what would that be then?
think i cannot avoid raycasts and only use math, i mean, how?
Did you not just go and look at the KeyCode documentation when I mentioned using them?
NumPad1 etc. I think. if you just type KeyCode. (with the period), your IDE will bring up a list of everything you can add.
@trail hull
- mouse position to world position mapping (or operator) returns a ray (ie a set of point)
- raycast can hit multiple objects
- so there is no any way to select exactly one objects just based on mouse position on screen
Camera.main.ScreenToWorldPoint(Input.mousePosition); returns a vector 3 not a ray
So I added visual scripting to my unity game because i thought it would just open an editor not create whole package, so my build to web failed for some reason so i deleted the visual scripting folder to see if it would help and now my game wont even play
that would've been smary, i now see what im supposed to do
ok you have a 2d point and you want to get a 3d point
how can you do this? one axis is missing
Might be able to use a raycast all to get the overlapping cells, then loop through them to select the middlest one.
okay now i see what you're saying
so why 2d to 3d mapping actually returns a ray not just one point
yes, but the user should select the depth let's say
whenever anyone mentions something you do not know, the very first thing you should do is look up the relevant documentation
you're right, thats mb
How?
so basically on other games 3d editors, what are them using for building the maps? I mean, does them force the user to build blocks near other blocks, does them let the user use the mouse and then scroll the wheel for the depth or how?
You could cast into a plane a certain distance away from the camera
that's the question, if there is a way to find it based on mouse position or something, without asking the user to select the depth or scroll the wheel
Usually it's the first hit surface.
private ArrayList<KeyCode> big = (KeyCode.Keypad0, KeyCode.Keypad1, KeyCode.Keypad2, KeyCode.Keypad3, KeyCode.Keypad4, KeyCode.Keypad5, KeyCode.Keypad6);
alright so i've got this now, which is obviously wrong but i don't know what to do if i want it to work
the first on the ground right?
actually i suggest scroll the mouse wheel and let the user set the sensitivity
a famous "3d voxel editor" is mineraft
That's impossible as Tina was trying to tell you many times. Mouse position only has info about 2 axis. There's missing info for any guess.
close
private KeyCode[] big = new KeyCode[] {KeyCode.Keypad0, KeyCode.Keypad1, KeyCode.Keypad2, KeyCode.Keypad3, KeyCode.Keypad4, KeyCode.Keypad5, KeyCode.Keypad6};
No. The first hit object in front of the camera.
ahh that makes much more sense
but this will allow the user to always build on the first layer and will never be able to draw behind
so now a for loop to loop through it
Well, that's if you even consider the grid. Unity and other editors don't limit the user to a grid.
yeah working on it rn
In the first place, making it a physical grid with colliders is not a great idea imho.
Is it a good idea trying to make player movement without using the "Update()" method and just using send message from "Player Input" component? I don't know if it is common to turn gravity on and off depending on player's state:
[SerializeField] Camera cameraRef;
[SerializeField] float moveSpeed = 10.0f;
[SerializeField] float jumpStrenght = 6f;
Rigidbody rb;
[SerializeField] float speed;
[SerializeField] bool doubleJumpReady = true;
float lookSensitivity = 0.05f;
Vector2 moveInput;
Vector3 currentRotation;
Vector3 velocity;
Vector3 cameraRotation;
void Start()
{
rb = GetComponent<Rigidbody>();
currentRotation = transform.rotation.eulerAngles;
}
void Update()
{
//empty
}
private void OnMove(InputValue inputValue)
{
moveInput = inputValue.Get<Vector2>();
Move();
}
private void Move()
{
if (rb.useGravity && Physics.Raycast(transform.position, transform.up * -1, out RaycastHit hitInfo, 1.001f))
{
if (hitInfo.transform.gameObject.layer == 0)
{
rb.useGravity = false;
moveSpeed *= 2;
}
}
float velocityY = rb.velocity.y;
velocity = (transform.forward * moveInput.y + transform.right * moveInput.x) * moveSpeed;
velocity.y = velocityY;
rb.velocity = velocity;
}
private void OnJump()
{
if (Physics.Raycast(transform.position, transform.up * -1, out RaycastHit hitInfo, 1.001f))
{
if (hitInfo.transform.gameObject.layer == 0)
{
doubleJumpReady = true;
rb.useGravity = true;
moveSpeed /= 2;
rb.AddForce(Vector3.up * jumpStrenght, ForceMode.Impulse);
}
}
else if (doubleJumpReady)
{
doubleJumpReady = false;
rb.AddForce(Vector3.up * jumpStrenght, ForceMode.Impulse);
}
}
private void OnLook(InputValue inputValue)
{
Vector2 lookDelta = inputValue.Get<Vector2>() * lookSensitivity;
cameraRotation = cameraRef.transform.rotation.eulerAngles;
cameraRotation.x -= lookDelta.y;
cameraRef.transform.rotation = Quaternion.Euler(cameraRotation);
currentRotation.y += lookDelta.x;
transform.rotation = Quaternion.Euler(currentRotation);
Move(); //Updates direction
}
oh my god bro the strength spelling hurts me on another level 😂
Whoops
trying to make an inventory system for my game using ui item script player pickup scrip ui managmet scrip and inventory manager if anyone knows what there doing regarding this i would apreachiate input as i am getting a bit lost
What part are you getting lost with?
everything my coding still are minimal and i am using chat gpt
if you are willing to go on call i can share screen
you're not gonna get much code help if you use ChatGPT lmao
@languid spire i've done a list iterating through it, and its throwing "IndexOutOfRangeException: Index was outside the bounds of the array"
ok man u do u im just trying to make somthing and ive been on the platform for 2 weeks i think ive done a hell of a lot but i cant learn c sharp in a week
show your code
correction: ChatGPT has done a hell of a lot. not you
yeah one moment
it might be hard to read idk
for (int i = 0; i <= big.Length; i++)
{
if (Input.GetKey(big[i]))
{
calibratedMarkerTransform = MarkerTransforms[i];
calibratedObjectTransform = ObjectTransforms[i];
}
}
for (int i = 0; i <= MarkerTransforms.Count; i++)
{
if (MarkerTransforms[i] != calibratedMarkerTransform)
{
MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = false;
}
else
{
MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = true;
}
}
@languid spire the code is pretty much supposed to sort through a special compass to see what its calibrated to detect, then later down the line it runs the code to display the position of the calibrated objects
Everyone's just trying to make something, but the difference between those who are and aren't is that some have actually taken the time to learn the skill rather than going 10 layers deep with AI and having no idea how they got there.
Nobody learns a new skill in a week, thinking you should is being unreasonable to yourself.
You can always start to !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the whole compass part works, its just calibration that needs work
ive done all the other code bro not going to have afight new year new life
ok 2 things
bool found = false;
for (int i = 0; i < big.Length; i++)
{
if (Input.GetKey(big[i]))
{
calibratedMarkerTransform = MarkerTransforms[i];
calibratedObjectTransform = ObjectTransforms[i];
found = true;
break;
}
}
if (found)
for (int i = 0; i <= MarkerTransforms.Count; i++)
{
if (MarkerTransforms[i] != calibratedMarkerTransform)
{
MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = false;
}
else
{
MarkerTransforms[i].GetComponent<MeshRenderer>().enabled = true;
}
}
i <= will always overshoot the array/list
good point
I KNEW IT
i < big.Length
my brain was screaming at me but i was telling myself that wasn't the case
i should've trusted myself on that one
alright im gonna implement that code now
ok @languid spire it works, but now i have a secondary issue very closely related
for some reason when its calibrated to 1, 2, 3, 4, 5 or 6 (which are all the objectives, 0 is calibrated to know where the enemy is) its pointing the same direction
which cannot be the case
I have no idea what you mean by that
i will show you a video, so its easier to explain
I really need help with this script i use to procedurally generate a map in my 2d game, the map generates just fine. using noise, but i cannot get the "GetHeightAtPoint" working, it never matches what i generated, it seems like it tells me some random height, idk. https://pastebin.com/dYKvZj1J
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 don't do videos
why? are you unable to view mp4 files?
no, I just hate them,
but it would help to understand what the device does and what the problem is
no it wouldn't because I would still not know anything about the underlying code
okay in that case
if (calibratedObjectTransform != null && cameraObjectTransform.GetComponent<Camera>().enabled)
{
SetMarkerPosition(calibratedMarkerTransform, calibratedObjectTransform.position);
}
this code runs in the fixed update
private void SetMarkerPosition(Transform markerTransform, Vector3 worldPosition)
{
Vector3 directionToTarget = worldPosition - cameraObjectTransform.position;
float angle = Vector2.SignedAngle(new Vector2(directionToTarget.x, directionToTarget.z), new Vector2(cameraObjectTransform.transform.forward.x, cameraObjectTransform.transform.forward.z));
float compassPositionX = Mathf.Clamp(2 * angle / Camera.main.fieldOfView, -1, 1);
markerTransform.localPosition = new Vector3(0.5f * compassPositionX, 0, -0.00453125f);
markerTransform.GetComponent<MeshRenderer>().enabled = (markerTransform.localPosition.x > -0.4495 && markerTransform.localPosition.x < 0.4495);
}
this is the void which it is running
the device functions as a compass, but like one of those compasses that you get at the top of your screen in some games, to show where objectives are
currently, when i set the device to detect 1, 2, 3, 4, 5 or 6 its all pointing in the same direction
which is not what it should be
it should be pointing towards objective 1, 2, 3, 4, 5 or 6
Ok, so why is there absolutely no debugging in that code so you know what is happening?
Hey guys, I'm trying to render a parametric sphere mesh but it isn't getting rendered correctly. I think there's something wrong with my indexing but can't find it.
https://gdl.space/igikubudey.cs
i know with certainty that the code works, i previously debugged it and it points at what i want for the enemy and stuff
its just that when its one of the objectives, it always points at objective 1
which is bad
those statements are contradictory, either the code works or it does not
should i ask this in advanced
the code points at things, its just pointing at the wrong things when its calibrated to 2, 3, 4, 5 or 6
does that make sense?
dont understand how you create sphere but look like you missing one step (connect the last iteration to first iteration
ie i==UResolution - 1 and j==VResolution - 1
I really need help with this script i use to procedurally generate a map in my 2d game, the map generates just fine. using noise, but i cannot get the "GetHeightAtPoint" working, it never matches the map i generated, it seems like it tells me some random height / the height of an entirely other map, like nothing even close to what its supposed to be. idk, because everything to me seems like it should work, but it doesnt. https://pastebin.com/dYKvZj1J
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.
F(u, v) = [ cos(u)*sin(v)*r, cos(v)*r, sin(u)*sin(v)*r ], I'm using this parametric form of the sphere equation. I was thinking the same thing it looks like the last strip is missing but I don't know how I can connect it really
one thing I can see is you should probably not be calling this if nothing has changed. So maybe make the found bool global and use that
why would i make it global for that?
i completely forgot how to get a point by theta and phi and radius and i dont want to do the math
you should store the result points of first iteration by theat or phi (you can use hashmap since most likely you will getting the exact result when calculate the angle) then you can just get the index of vertex back and create the triangle
so that the code only executes when a key is pressed
but it needs to constantly be running the void
private void SetMarkerPosition(Transform markerTransform, Vector3 worldPosition)
{
Debug.Log(markerTransform);
Vector3 directionToTarget = worldPosition - cameraObjectTransform.position;
float angle = Vector2.SignedAngle(new Vector2(directionToTarget.x, directionToTarget.z), new Vector2(cameraObjectTransform.transform.forward.x, cameraObjectTransform.transform.forward.z));
float compassPositionX = Mathf.Clamp(2 * angle / Camera.main.fieldOfView, -1, 1);
markerTransform.localPosition = new Vector3(0.5f * compassPositionX, 0, -0.00453125f);
}
this code needs to run every frame. that is crucial
I'm so sorry but I couldn't quite understand what you meant. Why would I need to use a hashmap instead of storing the points on surface in the vertices array
well it wont run every frame if it's called from FixedUpdate
i meant physics update, i am a fool
simple example of create a sqaure
CB
DA
you will calculate A then B then C then D finally go back to A to create the DA edge, so you can store the index of A by hardcode or look up table
btw i think you can hardcode the iteration of index anyway, you probably will store the vertex at some determistic way
0
1
2
3
4
5
6...
okay i'm thinking
wouldn't this result the same as what I'm doing now though?
Vector3 p0 = ParametricSphereFunction(u, v);
right now i'm picking a point on the surface and right after adding it to the vertices array i'm creating a triangle using that point. I don't go through the vertices array to create the triangles
but you only create the triangles from 0 to UResolution - 2, you block it by if statement
as the same as i only create the edge of AB BC CD but missing DA
yeah that makes sense
ok i'll try to change the algorithm then, thanks for the help
If I wanted to draw a background for my unity game should I make the drawing the same scale as the camera or is their an easier way.
What you're describing would be a bug, and I don't think it's the case. Possibly something is wrong with your keyboard.
cyl.localEulerAngles = Quaternion.Euler(0,i * 45,0);
i feel like i've done this a million times, but why isn't this working?
What isn't working about it?
Wait sorry
You are assigning a quaternion to a vector3 property
Cannot implicitly convert type 'UnityEngine.Quaternion' to 'UnityEngine.Vector3'
Oh would be localRotation =
thats the ticket
Or use localEulerAngles = new Vector3
cheers
wait why tf does altering y and altering z do the same thing @wintry quarry
Gimbal lock probably?
!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.
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Traps"))
{
Die();
deathSoundEffect.Play();
}
}
private void Die()
{
anim.SetTrigger("death");
rb.bodyType = RigidbodyType2D.Static;
}
private void RestartLevel()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}```
I have a pretty basic death script here but im confused on why the function "Die" hass to be called in order to take effect but not RestartLevel
you failed
Both need to be called for the code inside to be executed.
but i never acutally use the term "RestartLevel" in the code and it works as intended
i woudlve thought i would have had to add "RestartLevel" somewhere in here
surprisingly navmesh use a*
oh perfect
navmesh is the graph data structure not the pathfinding algorithm
Alright thank you, would you say navmesh is easy to impliment?
navmesh needs mesh renderer afaik
im not sure what that is
i googled you dont need it now
Oh okay, can you recommend any learning resources?
you can google lots of tutorual in youtube on how to use navmash in 2d
are they quite common tutorials or are they years old lol
make it so when you jump the drag is adjusted for in air movement and on ground drag for when you are on the ground
This might work
have you tried adjusting gravity to see if they does anything, changing mass might also work
I think you can let me double check
My apologies thats only in 2D. Are you accessing gravity or just using forces>
maybe using a constant gravity force will help. I'm not that brill at 3D and dont have much experience maybe someone else might have a deeper insight
You do have. Either you're calling it from somewhere else, or there is similar code somewhere else being executed. Code doesn't execute magically. You need to call it from somewhere.
it says theres 0 refrences in my code
i probably just dont understand coding well enough to get whats going on tho
Then this is not called anywhere. What makes you think that that coe executes?
the level restarts when i die
Try finding LoadScene by reference
you’re calling it somewhere
this is the closest thing to calling it i have in the script
or you’re might loading the scene by directly calling the unity api
It doesn't have to be in the same script.
If you see the animation before the level restarts I'm guessing it's triggered by the animator
right click the LoadScene method and select "find by reference"
i dont have any other code written to do with loading scenes
this?\
Then it's either what Nitku said or you're invoking it from a button/unity event
leme rewatch the video and see if i missed something
oh wait
i think the death animation is a trigger for it
oh yeahh it is
sry i didnt realize
Hello, I wasnt to check if a bool has been false for 3sec or more. If yes then run a certain function
Create a timer float for how long it has been false for.
In update, if it's false, add delta time to the timer, then check if it's over 3.
If it's true, set the timer back to 0.
if bool false start timer if timer over DoSomething
ahh thats so simple as compared to what I found on the internet and makes so much sense
thankyou
It probably involved coroutines. Those are great for a single-purpose timer that you just start and let run, but a coroutine with multiple "exit conditions" (bool becoming true or timer ending) is usually more complex than just manually timing it
Hello! I need help. I'm using this script to only one object in 1 scene from 2 scenes and I want to make it's optional to set up, not obligatory. How to make it optional?
The script is connected to two scenes
If not having a sharpnessCostText is a common occurrence that can happen through normal intended play, you can simply check if it is not null before attempting to set it
I have a simple platformer game with Photon and parrelsync and for some reason when I start the game (only sometimes) some assets randomly disappear even from the scene view. Does anyone have any ideas why that happens please? I dont know how to test it since its literally random
I am trying to use this to detect how long it has been since I got hit by the enemy and I am using this code to toggle the boolean but it is set to true for so of a time that the timer does not rest at all
You'll simply want to set the flag true in that function and evaluate it elsewhere - somewhere that occurs every frame.
Update:
if isHit == true
isHit = false
elapsed += delta time
if elapsed >= Time.time
do stuff``````
Hit:
isHit = true;
currentHealth -= amount;```
Is there a way to put the game in slow mo to get a better idea of what’s happening?
Only one line of code ever runs at a time. The isHit is true only when the next line runs before you set it back false
If you want to reset the timer, then reset the timer. Don't bother changing the boolean
You can pause the game at the top of the editor and then use the "next frame" button (the third one) to step through it frame by frame.
You can also alter the timescale, too, I've never used it for debugging (I'm doing it for a call-out tutorial currently) but I don't see why you couldn't do this to run your program in slow motion for testing purposes.
Time.timeScale simple script yeah
Well also think if you want your user to have a pause button
Unity makes it easy to slow/stop/speed up the flow of game time
And also keep things separate from that if you need to (like if you wanted music to keep playing while paused, etc)
For a pause i assume timescale would be 0?
does JSONutility.FromJSON validate variables ?
only in the sense that they are the correct type
yhh okay thats good enough thanks
You're better off using Newtonsoft/JSON.NET, because that one actually correctly parses data. I can imagine JSONUtility silently fails
are those already installed with unity/visual studio, and how would i use them in JSONutilities place
Quick question, are the Input Systems 1D Axis broken, or is it me? It does not give me continous values. Rather I get -1, and 1.
What have you mapped it to
download the package, use the new Json.net methods
the only thing JSON.net hates is unity Vector3 and whatnot
https://docs.unity3d.com/Packages/com.unity.nuget.newtonsoft-json@latest
Want to use one pedal for negative input and another for positive. Or should I just use Up and Down Actions instead? (Which is what I am implementing rn as a workaround)
Vertical is also Value and Axis like Horizontal on the screenshot.
for (int i = 0; i < buttons.Length; i++)
{
buttons[i].gameObject.SetActive(false);
}
is this a good approach to deactivate all the buttons in the title screen?
Sure, could also just use foreach
just deactivate the parent
making an array with them and insteand of repeating button.gameobject.setactive(false), using a for loop
coming from python i forget about it
i'm following a tutorial and i thought i could use this but yeah that's much simpler
Hello, in my code I return a null since I'm am not sure what to return,
I have a score that is set up so that when it reaches a score of 25 the objects will stop spawning ( this because of the return null ) then the player can walk up to the set teleporter to teleport to the next room, where the spawn area has to change but that doesn't happen.
I don't know how I can fix my problem
can someone help me with getting something to snap to a grid, im kinda stuck at this code. https://pastebin.com/ueVU8qgK
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.
pastebin sucks! stop using it plz
then you didn't lock it
where are you running this function
what should i use instead?
any of these
!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.
pastebin sucks
oh, well heres the new one https://hastebin.com/share/ifetetazey.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
why would i need "public" paste be bigger DIV than actual code 😵💫
put debug.log make sure that function is running
if it is you have another script unlocking it
whats problem you're facing?
How can I do TryGetComponent in children in a performant manner?
if its locked it will be cetered, if its not locked then it wont be center. You have another one overriding it then
search your script
It says GridLayout doesnt have a definition for GetCellCenterWorld at line 17
make your own extension method
i thnk that should just be Grid no ?
yeah i thought that too, but that just gives me the same error
@rich adderExtending TryGetComponent?
probably using the wrong namespace one
no Transform prob, GetComponentInChildren
how did you search
show new error
https://hastebin.com/share/ucayiyahad.csharp and it says Grid doesnt contain definition for "GetCellCenterWorld"
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hi I have this custom struct inside my MonoBehaviour:cs [System.Serializable] public struct CameraZone { [SerializeField] public List<Transform> cameraCheckpoints; private Vector2 minCoordinates; private Vector2 maxCoordinates; private Vector2 centreTarget; }
and you can see I have private members, but this is not what I want. As it is serializable, I just want the currently private members to just not be visible in the inspector, however accessable and modifiable by the monobehaviour it is in. How can I do this?
do you have any custom scripts named Grid ?
is there a question ?
OHHHHH
yeah i do
ye it accidently sent, I edited it
make them properties
it works fine if you click the gameview, only time it doesn't if you press escape
Hello, in my code I return a null since I'm am not sure what to return,
I have a score that is set up so that when it reaches a score of 25 the objects will stop spawning ( this because of the return null ) then the player can walk up to the set teleporter to teleport to the next room, where the spawn area has to change but that doesn't happen.
I don't know how I can fix my problem
what how?
lookup properties
[System.Serializable]
public struct CameraZone
{
[SerializeField] private List<Transform> cameraCheckpoints;
public Vector2 MinCoordinates { get; private set; }
public Vector2 MaxCoordinates { get; private set; }
public Vector2 CentreTarget { get; private set; }
}```
!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.
ooh them, alright but why private set, why not just set? I want to be able to set it inside the monobehaviour, just not in the inspector. Will that work?
ohh thought you want to only set them through this SO
why exactly using SO for mutable data, if you change this one you will change values in all of them
Well, I just wanted to organise my data as a field in my monobehaviour is a list of these structs. Are you suggesting I create a custom class for this or something?
depends all what you're doing, if you only need hold data its fine but just be aware that if you change 1 scriptable object you will change all data of the same SO
eg if one SO has MinCoordinates as 0,3
then anything that has so with MinCoordinates will have 0,3
// Function to determine the spawned target based on the player's score
GameObject GetSpawnedObject()
{
// This MAIN Object Spawner Manager function for the spawn areas || NOTE: the other Object spawner area scripts are copies from this "main" script
if (ScoreManager.scoreCount == 25 || ScoreManager.scoreCount == 50 || ScoreManager.scoreCount == 75 || ScoreManager.scoreCount == 100)
{
Debug.Log($"Score is {ScoreManager.scoreCount}, no targets will spawn.");
// Set up logic for when the score matches specific values
teleporter.SetActive(true); // Activate the teleporter
// Enable player movement
if (playerMovement != null)
{
playerMovement.EnableMovement();
}
return null;
}
else if (ScoreManager.scoreCount >= 50 && ScoreManager.scoreCount < 100 && TargetS != null)
{
Debug.Log("Selected TargetS");
maxObjects = maxObjectsTargetS; // Change maxObjects for TargetS
return TargetS;
}
else if (ScoreManager.scoreCount >= 25 && ScoreManager.scoreCount < 50 && TargetM != null)
{
Debug.Log("Selected TargetM");
maxObjects = maxObjectsTargetM; // Change maxObjects for TargetM
return TargetM;
}
else if (ScoreManager.scoreCount < 25 && TargetL != null)
{
teleporter.SetActive(false); // Deactivate the teleporter
Debug.Log("Selected TargetL");
maxObjects = maxObjectsTagetL; // Reset maxObjects for TargetL
return TargetL;
}
please use links like bot suggested,
not easy to read code like this, esp mobile
So essentially the 1st field is given by the "level designer" and the remaining 3 fields are precalculated and stored to save time in each frame update. I think I may have to switch to classes but I'm not exactly sure.
think SO similiarly to a static class (in terms of mutable data)
Sorry I edited it
do you know what links are?
yes I do
public class Shoot : MonoBehaviour
{
public GameObject bulletPosition;
public GameObject bulletPrefab;
[SerializeField] private float bulletSpeed;
private Camera cam;
[SerializeField] private VisualEffect muzzleFlashEffect;
public float bulletLife = 4f;
[SerializeField] private Animator animator;
[SerializeField] private VisualEffect muzzleFlash;
public bool isShooting = false;
[SerializeField] private GameObject muzzleLight;
private void Start()
{
cam = Camera.main;
animator = GetComponent<Animator>();
muzzleLight.gameObject.SetActive(false);
}
private void Update()
{
if (Input.GetMouseButtonDown(0) && !isShooting)
{
isShooting = true;
ShootBullet();
HandleVisuals();
StartCoroutine(shootDelay());
}
}
public void ShootBullet()
{
GameObject bullet = Instantiate(bulletPrefab, bulletPosition.transform.position, bulletPosition.transform.rotation);
//Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
RaycastHit hit;
if (Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, out hit, Mathf.Infinity))
{
Debug.Log(hit.point);
Vector3 bulletDirection = hit.point - bulletPosition.transform.position;
bullet.GetComponent<Rigidbody>().velocity = bulletDirection * bulletSpeed;
}
else
{
Vector3 bulletDirection = (Camera.main.transform.position + Camera.main.transform.forward * 1000) - bulletPosition.transform.position;
bullet.GetComponent<Rigidbody>().velocity = bulletDirection * bulletSpeed;
}
Destroy(bullet, bulletLife);
}
Can anyone help me figureo ut why my bullet zooms away at light speed when i am not pointing at a target? it works fine if i hit an object with the raycast
!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.
god people who mindlessly paste their entire classes
so use them..
bit entitled
ok ill put it in one of those code block things
https://hatebin.com/etcictfeey
Can anyone help me figureo ut why my bullet zooms away at light speed when i am not pointing at a target? it works fine if i hit an object with the raycast
this isnt your first time around here afaik.
Shouldnt you know entire class go inside a link?
it wasnt my entire class i had other functions i left out
why the hell would you purposefully omit functions 🤔
It speeds away because the distance is about 1000 units away and you set the velocity to that times bullet speed, so presumably several thousand units per second
hey guys, so I have prviously asked a question here, but no one helped me fix a problem I have. Can anyone check what I wrote in here to know what the problem is?#💻┃code-beginner message
also the direction isn't normalized
oh okay, that was my fix for when it didnth it an object
so hit distance also affects it as you described in problem
should i make the 1000 a smaller number?
Velocity should be set to bulletDirection.normalized * bulletSpeed
thank you
same thing earlier when the raycast does find a target, now the bullet speed depends on how far the target is
although I don't see why you have to do the raycast in the first place, it looks like the bullet goes to the same direction in either case
i was having problems with the bullet not going to the centre of my screen
the camera raycast was my solution and its working out alright
What happens when it runs?
did you solve the problem or are you having problem pasting code in PasteLink provider
is there a way to get around dictionarys being non serializable
im tryna have it save from editor to play mode but it gets cleared on play
Hello there! when I try to create a URP shader it just becomes a pink missing texture. Anyone knows what's up with it?
You could either get a serializable dictionary asset or just serialize two lists and build the dict from those lists at runtime
ah alright ty
i got stuck in an infinite loop how do i stop the program
End Task
list of structs too (kvp struct)
nono i mean im in the unity editor i don't want to lose what i've done
i got stuck in an infinite "while" loop
mate no other way out but to end task
if you didn't save, you're fooked
always ctrl+s everytime I press play 🤷♂️
No, the problem is more that when I return something its clones the GameObject, since the function is referenced in a while loop.
please put the entire class and send link via sharecode site like https://hatebin.com
make sure it showing how you instantiate
everything runs, it just seems that the add force on the function checkIfSuddentChangeInDirection() is not doing what it is suppoesed to do
you know adding force
Does it give an error?
no
public class BulletCollision : MonoBehaviour
{
[SerializeField] private Rigidbody rb;
[SerializeField] private float bulletForce;
private void Start()
{
rb = GetComponent<Rigidbody>();
}
private void OnCollisionEnter(Collision objectHit)
{
if (objectHit.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
print(objectHit.collider.name);
}
if (objectHit.gameObject.layer == LayerMask.NameToLayer("Humanoid"))
{
print(objectHit.collider.name);
objectHit.gameObject.GetComponent<Rigidbody>().AddForce(rb.velocity * bulletForce, ForceMode.Force);
}
}
}
hi again, im not sure if this is programming or physics related (maybe theyre similar enough so that it doesnt matter) but a rigidbody component on a gameobject is causing my bullet to hardly ever detect the collision and phasing through it. I can send a video butim not sure if thats allowed lol
cyl.localRotation = Quaternion.Euler(-90, 0, i * 45);
no matter how i alter this, it doesn't rotate on the right axis. why can't i rotate it how i want?
This may help.
The preeminent article on game timesteps is Gaffer On Games: “Fix Your Timestep!” . Cached version, as the article occasionally goes down. The article gives a great amount of context for implementing a game engine time step in a couple of different ways. Unfortunately, while this is useful, it is
We don't know how you want it to rotate so that's pretty much impossible to answer
select the object in scene view and play with the rotation in the inspector until you find the right axis
This may sound completely stupid (if you haven't solved it already), but you do have colliders on your bullet and humanoid and you have checked that collision between those layers are enabled in your project settings?
yep
im trying to check overlapping objects now
i dont know why rigid bodies are affecting it
https://hatebin.com/kzeyvduqzs
why it bounce so weirdly??
sorry I don't know how I can save me hatebin and sent it to here
paste the code there, click save. Copy link in your browser address, send link
I did but it gives me this minus
did you put any code there?
use any of these sites
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
they all do the same thing
I pasted my hole call but still the same result, I'll try the other sites now
Hatebin never worked for me aswell it's bugged
Hello my enemy (rigidbody) is rotating when hit by another rigidbody even when it has freezeRotation to true. I don't rotate of this object at all and only move it in 2d towards its target with addForce. Does someone maybe know where it could come from ?
when I return something its clones the GameObject, since the function is referenced in a while loop.
what exactly is wrong and what do you expect to happen?
fixed it now thank you to those who helped
I don't really know how to explain but I try my best,
I would like it to stop at 25 but starts again when ( already made that code ) the player went through the teleporter
start what again ?
also how much of this script is written by AI
a lot of weird statements here
Hey, does someone knows how can i join a project that one friend shared me with unity version control? He has invited me with my mail... but i can't find the project anywhere and i'm incapable of start editing it hehe. Please... i need help :>
#💻┃unity-talk
should be under Add Remote Project in Hub if they added you correctly
Thaankss
i have all these different transforms, yet they all return the same vector3 position. specifically, they all return the position of the first one (uniglow). if i change one of the list items to a random cube for example, it returns the position of that cube where i want it, but for some reason these glows and the objects related to this return position 1. whats going on?
Most part of the scripts,
to start the target spawning again
This is a fragment of a script that I made to drop player-held items in my game. This is the part of the script that makes the item fall downwards until it touches the floor, where it stops. The problem is, since I'm using Physics.CheckSphere() to detect this, some objects clip into the floor because they are made of only one GameObject. What alternatives are there for Physics.CheckSphere() that would do this correctly?
while (running)
{
newModel.transform.position = new Vector3(newModel.transform.position.x, newModel.transform.position.y - 0.01f, newModel.transform.position.z);
for (int i = 0; i < childCount; i++)
{
if (Physics.CheckSphere(modelBody.transform.GetChild(i).transform.position, 0.01f, ground))
{
running = false;
}
else if (Physics.CheckSphere(modelBody.transform.GetChild(i).transform.position, 0.01f, incinerator))
{
Destroy(newModel);
running = false;
}
}
if (loopCount > 1000)
{
Destroy(newModel);
running = false;
}
loopCount++;
Debug.Log(loopCount);
}
So start the coroutine again ?
My suggestion is to stay away from AI coding since it provides 0 learning and confusion when something breaks/goes wrong since you wouldn't know how to debug it. The code seems overly "complex" and jumbled for something probably easily done with a few lines of code
Yea, thanks for your given feedback, I will change it and use far less AI for those coding things, still thank you
@rich adder to add someone to my project shared on unity version control i need to do it with that option?
and then to introduce their mail there, right?
If i wanted to make a idle game, is this good to calculate how much i earn when offline?
private void OnApplicationFocus(bool hasFocus)
{
if (!hasFocus)
{
lastFocusTime = DateTime.Now;
animator1.speed = animationSpeed;
}
else
{
animator1.speed = animationSpeed;
TimeSpan offlineTime = DateTime.Now - lastFocusTime;
int moneyToAdd = (int)(offlineTime.TotalSeconds / 15);
if (moneyToAdd > 0)
{
moneyadd(moneyToAdd, 1);
data.lastLoginTime = DateTime.Now;
Debug.Log("You earned " + offline + " money while away." + offlineTime.TotalSeconds);
offlineText.text = "You earned " + offline + " money while away.";
moneyText.text = "Money: " + data.money.ToString("F2");
}
}
}```
for android btw
At some point the phone will kill the app so the values need to be saved to persistent storage
Wrong channel go to code advanced 😭😭
ah alr cause im a beginnner and thats why i thought this should be here
What even is this abomination
no this is fine
ay idea how should do it?
You can add strings in c#?
Playerprefs should be good enough for this purpose
whats that and what does it do?
