#💻┃code-beginner
1 messages · Page 78 of 1
If you're trying to launch something just set its velocity.
Like targetRb.velocity = launchDirection.normalized * launchSpeed
hello i ran this code but it gave me and error
This isn't really a Unity issue
There is a !cs server
But it looks like the error is cut off, what does it say?
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
Oh, did you SAVE the script? Maybe that is the issue? The yellow on the left means unsaved. Dunno if that affects the build, but it certainly would affect unity compilation
I'm guessing that the top level statement (program wrap and entry point) are already applied. Try removing it and just print to console.
so im trying to get boats to float via the HDRP water system, this is my code and it works, but is there a way to expand it so i can have the boat not just move straight up and down but move via points so like the front would be higher than the back? ```using UnityEngine;
using UnityEngine.Rendering.HighDefinition;
public class Fit : MonoBehaviour
{
public WaterSurface targetSurface = null;
// Internal search params
WaterSearchParameters searchParameters = new WaterSearchParameters();
WaterSearchResult searchResult = new WaterSearchResult();
void Update()
{
if (targetSurface != null)
{
// Build the search parameters
searchParameters.startPosition = searchResult.candidateLocation;
searchParameters.targetPosition = gameObject.transform.position;
searchParameters.error = 0.2f;
searchParameters.maxIterations = 8;
// Do the search
if (targetSurface.FindWaterSurfaceHeight(searchParameters, out searchResult))
{
gameObject.transform.position = new Vector3(gameObject.transform.position.x, searchResult.height, gameObject.transform.position.z);
}
else Debug.LogError("Can't Find Height");
}
}
}
Ah yeah, I see in the cs server they used a .net framework project template. Definitely what you said
ah, yeah probably don't want to start with one of those
usually I go with the console/windows app template
otherwise blank
Anyone know why my Node isnt on the Player or enemy?
you might wanna check #854851968446365696 for what to include when asking for help. and also maybe realize that we don't have context for what is supposed to be happening or what this screenshot is supposed to convey as the issue
no one know
looks like the mapping from world space to grid is wrong
psd photoshop doc?
yes
it's JPG
sad
Does anybody know why my background is serialized so wrong in my custom editor?
public bool useBackground = true;
[HideInInspector] public ComponentColorSwitch<Graphic> background;
Custom editor class: https://gdl.space/fatodezane.cs
Guys could anyone recommend me Unity C# book - like for dummies type.
What I need is something that I can just reference "What is method" , "How to make For loop" .... basically explaining every important concept. SO its easily referencable for my absentminded self 😂
Could be free PDF or payed PDF...or even website if there is such
Do you want to learn C# from the start?
Well yes. I am artist that want to make games. I allready started on tutorials and such. And I am making good progress. But everytime I let say dont do something, and I start again I have to go back to youtube vid to look it up. And its vaste of time.
Having a book open would be better
So I am not like 0% begginer. Let say 10%
Tbh am the same am in lvl 1 IT in college and i have just been researching how to develop my own app/ game but youtube vids are soo annoying
I see, I haven't ever used a book, so I cannot recommend one. But it's strange that you forget everything. Maybe you just need more practice? There's a plenty of sites for this.
Revisiting C# basics material is the way
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
http://rbwhitaker.wikidot.com/c-sharp-tutorials
That is my problem with code. WHat can I do
more practice 😁
This is pretty good. Thanks
I would like to recommend you a very nice site
https://exercism.org/tracks/csharp/exercises
Whats the best app or tutorial to start designing games for a beginner?
you have to keep coding, that's it. repitition and learning how to create gameplay and systems help accumulate that base knowledge . . .
how did you get good at becoming an artist? i bet it's similar; practice . . .
First do c# then unity, trying to learn both is going to be way harder. If you're unsure of what to code, I say do challenges online which give you some guide of what problems exist and what you can solve. Problems range from printing out "Hello world" to solving complex data questions, on sites like leetcode or whatever you choose to use.
I used to tutor in coding, and regardless of how long someone's been coding its quite clear when they havent done thought provoking challenges. It provides very good knowledge on how to debug when something is wrong
Its not that... I just need a reference for syntaxes and stuff. Also and especially for things you dont use all the time.
I dont need guide on how to code. Just reference
Do some easy stuff then do some code reviewin
I have been coding CSS forever now. And I still all the time go to CSS school site to check syntaxes
You're going to spend more time trying to learn in this way. If you dont thoroughly understand the fundamentals, you're going to be stuck with c# AND unity problems. Sorry to say, but css is not at all comparable to unity and c#
I understand the fundamentals. This is exactly what I am saying.
I just forget the syntax
I think the process of learning both is very comparable, which is looking up things as you go
implying I know the syntax. My ide just does it for me
That is point also 😄
Then realistically google is going to be your best resource. As long as you know what to google, the first 1-3 results on google will have exactly what you want
itll be quicker than trying to find the same answer in a wall of text in a textbook for example, where you cant quickly search keywords since words like method void etc will appear hundreds of times
Problem is that it mostly comes up as youtube videos. People dont write these guides as text anymore ( not on web ) , and if its just like answers in some forums. And then they are very specific to the question
Its waste of time
chatgpt is fine honestly
People still write stuff. Microsoft also has extensive written material on their site https://learn.microsoft.com/en-us/dotnet/csharp/
especially for starting on new languages it's pretty good at giving you advice on basic stuff
With the examples you listed, ( "What is method" , "How to make For loop"), these would definitely bring up the microsoft docs or some other good website. If you're talking about how to do stuff in unity, then yea unfortunately most guides are just long videos. A lot of them are from people who dont really know what they're doing either
I use video guides more as an indicator to what exists, like stuff in the unity api i didnt know
That is my goto solution
obviously it's better to read the documentation, but sometimes you can miss little tidbits which it'll clear up for you usually
Its amazing how good is Chat GPT for learning code, I must admit
Anyway. Thanks guys 🙏
ye
How do I read a .txt file? I'm developing an Android app and I've given to understand that the process is different than normal C#. Please ping me if you reply - TIA!
where are you reading the file from?
A script
which path
I have a large list of 10000 words and storing it in memory seems to crash the Editor.
So I will store it in a text file and read from there, line-by-line, hopefully so that the entire thing isn't stored in memory at one time.
But I'm new to C#, so no idea how to deal with files, let alone read line-by-line.
Don't really care, it just has to be packaged with the application.
I suppose that means it'd be in Assets? Doesn't matter for the purposes of the app.
you have 2 choices.
- Store the file in a Assets/Resources folder and use Resources.Load to read it
- Store the file in Assets/StreamingAssets and use UnityWebRequest to read it using Application.streamingAssetsPath
What's the difference between them? What's easier? Which one would better facilitate my line-by-line strategy? Thanks for replying 🙂
May I suggest you go and read the Unity docs on both of them
Certainly, I'll go check them out now. Just really quickly - which one do you think would better suit my needs? I'd like someone's opinion as circumstantial advice is hard to come by 🙂
In your case very little difference. Option 1 will be easier to code
Great, thank you. I'm going to have to figure out how to read it line-by-line as all the examples here load the entire file at once...
It'll be a fun challenge though - thanks for all your help!
if you really want to use the standard System.IO.File methods, which includes a ReadLine, you can copy either of the data produced by the above options and write it to Application.persistentDataPath then read it from there
Great, I'm off to read those docs. Thank you so much!
Hey guys can you help me animate emission property of unity material. I want it on and off randomly
Message #💻┃unity-talk
I have made this class for nodes:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NodeScript : MonoBehaviour
{
[SerializeField] private int TravelCost = 99999;
public int getTravelCost() { return TravelCost; }
public void setTravelCost(int inCost) { TravelCost = inCost; }
[SerializeField] private int[] indexCoord = new int[2];
public int[] getIndexCoord() { return indexCoord; }
public void setIndexCoord(int[] index) { indexCoord = index;
Debug.Log($"I am {gameObject.name} and INDEXCOORD WAS JUST CHANGED TO {index[0]} , {index[1]}");
}
private bool containsEntity = false;
public void enterNode() { containsEntity = true; }
public bool hasEntity() { return containsEntity; }
public void setContents(bool inContents) { containsEntity = inContents; }
private GameObject entityContained;
public void setEntityContained(GameObject inEntityContained) { entityContained = inEntityContained; }
public GameObject getEntityContained() { return entityContained; }
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
As you can see, indexCoord is PRIVATE and logs a message every time it is changed.
However, at some point in my game, whenever a certain task is done, which I can elaborate on further if necessary but would take too long to explain here, one node's indexCoord changes. Only one. I normally would be able to figure this out, but the node doesn't log any message when it changes this time, which should be impossible because it is private. I know that the debug log works because when the node's index is initially set, it DOES output that message.
help how does something change it if its private 😨
sorry about messy code, im generally new and in a rush
!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.
Mornin' all, not really sure what I'm doing wrong here so hoping someone can see my mistake, basically using a coroutine to lower the intensity of a point light (muzzle flash point light). The coroutine triggers fine, but the light doesn't 'fade out' like it should. Any ideas? 😕
IEnumerator MuzzleFlashLight(bool leftLastFired)
{
if (leftLastFired == true)
{
muzzleFlashLightRight.intensity = maxMuzzleFlashLightIntensity;
if(muzzleFlashLightRight.intensity > 0f)
{
muzzleFlashLightRight.intensity -= muzzleFlashLightFadeRate;
}
}
if (leftLastFired == false)
{
muzzleFlashLightLeft.intensity = maxMuzzleFlashLightIntensity;
if (muzzleFlashLightLeft.intensity > 0f)
{
muzzleFlashLightLeft.intensity -= muzzleFlashLightFadeRate;
}
}
yield return null;
}
maxMuzzleFlashLightIntensity is set to 1f.
muzzleFlashLightFadeRate is set to 0.1f.
rather than yield return null use yield return WaitForSeconds(float timeInSeconds) or some other wait function
because atm i think your yield return null doesnt do anything to add a delay between fade intervals
no loop, just sequential statements
Hook up the vs debugger and throw a break point onto the field
At a guess you are passing an index array which does not have 2 entries, thus causing the Debug.Log to fail. Try logging the length of the input index array
hey everyone, im trying add jumping in my game, the problem is that at the end of the jump its like the player hits some sort of ceiling and immediately stops, it is extremely jarring, any clue on how to fix this?
if(canJump && jumpInput > 0){
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
canJump = false;
Debug.Log($"adding force to jump {rb.velocity}");
}```
does that trigger every time its changed and say where its changed from?
i will try this!
you should use vecto2int or int2, to save memory and prevent the length of array passed < 2
also add a null check
steve's probably right though but I would assume you'd get some errors in the console
see this is weird asf because im getting no error messages
ill put a pure string debug log before indexCoord = index just to show when it runs and log the index's length and stuff
and see if that tells me anything
because when the indexCoord is being changed anomalously its not just changing to null or anything
its changing to another valid index
but not the correct one
Any time your program reaches the point it'll pause the program and give you the current stack trace and you can even hook it up while the program is running
i ran it with the new debug logs, nothing
nothing at all
doesnt run anything in there yet somehow changes the indexCoord
i am clueless
is there any way AT ALL to change a private attribute from outside the class, without using its setter??
setting breakpoint or remove the function calls to read the error and found out who call it
btw still recommend you use vector2int or int2 instead of array
if i change from int[] to int2 wont i have to change it everywhere else where setIndexCoord is called when the nodes are initially set
and wherever the indexCoord is read
how do i set a breakpoint lol
that way ill be able to see exactly when the change is made
of course, using reflection. btw you are not using properties so 'setter' is not the case here
whats reflection?
sounds like it might be it
because the anomalous change is always like
it sets the indexCoord to a coordinate in the same relative positione
every time
if you do not know what reflection is then you are not using it
unlikely
maybe this issue is somehow related to LeanTween
i know that the change occurs right after an object tweens to that node
you have to guarantee all callers passing a correct array (not null and length==2) to it if you using array
if you change it to vector2int or int2, you have to change all of getters and setters to it
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/properties
Ah, the only way to change the value of indexCoord without actually changing the value is if you are replacing the whole Node instance with a different one
nodes are never instanced in my build, they are already set in locations
and its name doesnt change so im pretty sure its the same one at least
of course they are instanced. They are Monobehaviours
my head hurts
well yeah but like during runtime they never are
as in like
by any scripts i made
no new ones, at least
the instances that exist are the ones already there
tell you what. why not duplicate your Debug.Log into the get method and prove that
also add the gameObject.GetInstanceID to the Debug.Log
ill try that
Coz I think you are calling get on a different object than you think you are
alright, changed it to this
public int[] getIndexCoord() {
Debug.Log("GETTING INDEXCOORD");
Debug.Log($"I am {gameObject.GetInstanceID()} and INDEXCOORD is {indexCoord[0]} , {indexCoord[1]}");
return indexCoord; }```
so this is just the get method
not supposed to change anything idk
thats fine
and you're not changing anything with the getter?
now make sure you log the gameobject instanceid of the gameobject you are working with
a gif to better explain my situation
So are you constantly using a force as you jump instead of once?
just once, when i press the space bar
so turns out i cant do this because for my pathfinding algorithm getIndexCoord() is called a lot
and to add debug logs in that causes INTENSE lag
long freezes
it would break around 120^2 times
Hmm, I guess you can probably log it then write to plain text and instead of the console
icl if i dont have this solved soon im just gonna have the indexcoord manually fixed every time something tweens to that node
because i am very much in a rush
this due tomorrow 🥲
Do I need to use async & await for database queries in C#?
local or remote database?
remote
maybe
you dont have to but it is better if you do
that is weird 😛
you need to stuck the thread before calling the method that use the data
but you can do other stuffs while waiting the data by async
Hello, I need help with the following problem:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private GameObject gameRules;
public GameObject otherPlayer;
public float speed;
public string horizontal;
public string vertical;
public bool faenger = true;
void Start()
{
gameRules = GameObject.Find("GameRules");
}
// Update is called once per frame
void Update()
{
Vector3 bewegung = new Vector3(Input.GetAxis(horizontal), Input.GetAxis(vertical), 0);
gameObject.transform.position += bewegung * Time.deltaTime * speed;
}
private void OnCollisionEnter2D(Collision2D collision)
{
UnityEngine.Debug.Log("coll");
if (faenger && collision.gameObject.CompareTag("Player"))
{
FaengerSwitch();
UnityEngine.Debug.Log("Switch!");
}
}
public void FaengerSwitch()
{
gameObject.transform.position = new Vector3(5, 0, 0);
otherPlayer.GetComponent<Transform>().position = new Vector3(-5, 0, 0);
UnityEngine.Debug.Log(faenger);
faenger = !faenger;
UnityEngine.Debug.Log(faenger);
otherPlayer.GetComponent<PlayerMovement>().faenger = !faenger;
}
}
I use this script for my two players who have to catch each other. The problem: Changing from faenger = true to faenger = false only works the first time, then faenger no longer changes when catching. I would be really grateful if someone could help, I'm really desperate right now and the internet couldn't help me either!
Thanks in advance!
!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.
oh, sorry
I meant use a paste site
After FaengerSwitch() what state are both in
Two oncollisionenter are called one after one then the faenger changes from true->set to itself’s and other’s to be false-> call other oncollision enter -> reverse the process
true & false
Nothing are changed finally
ah ok so it's just not changing is the problem
lets GOO chatgpt finally helped me
should add a cooldown buffer between tagging
i changed getIndexCoord() to:
public int[] getIndexCoord() {
return (int[])indexCoord.Clone(); }```
turns out getIndexCoord() was exposing indexCoord and allowing it to be changed
so now it returns a clone instead yippeee
i did not know that was a thing that could happen
yeah
but how is that possible if i teleport them before i change faenger?
Oh i misread it is setting itself’s to be false and the other’s be true, but the result should be the same
another thing too is for them to retag each other they probably need to move from the previous collision spot
arrays are reference type in C# (as well as lists etc..., anything that is a class)
Oh wait you block the call, i am wrong
think about it.
The players collide.
Both Players fire CollisionEnter
Both players change their own and the others faenger variable.
Then both are wrong
you probably need to change the initial value of faenger to false on one of the players
i did that in the editor
A B
T T
F T< after setting itself and other, first call on A
T F < after setting itself and other, second call on B
no, because the second call on B will not happen
You propagate the original value to other and reverse the one on itself btw
depending on the sequence of Collision enter
I'm not seeing T T or F F, more that until they remove theirselves from colliding it won't fire again.
but basically it would reset to the same state every collision
If you start with
A B
T F
Dont know if collision is called on A or B first
If A then
F T
then
T F
if B then
T F
F T
but how can it switch twice?
Need to add a global cooldown between collisions which both should be checking from
better idea would be to set a bool when colliding and unsetting it until they are far apart enough
But how can A&B call Switch if only one of them is true?
this is the sequence of events
Collision
CollisionEnter called on A
A changes the values
CollisionEnter called on B
B reads the values just changed by A
But after the switch there is no collision anymore because I teleported A&B or am I misunderstanding that?
the collision still happened
easy
static bool done=false;
private void OnCollisionEnter2D(Collision2D collision)
{
if (!done) {
UnityEngine.Debug.Log("coll");
if (faenger && collision.gameObject.CompareTag("Player"))
{
FaengerSwitch();
done=true;
UnityEngine.Debug.Log("Switch!");
}
} else done=false;
}
Thanks a lot!
that way only one players collisionenter will fire for each collision
I'm an idiot. Forget all of the above
just remove this
otherPlayer.GetComponent<PlayerMovement>().faenger = !faenger;
from your code and you will be fine
also move this
faenger = !faenger;
to the end of CollisionEnter
i added a rigid body to a gameobject but it falls through all the objects i have is there anyway to fix that?
Thank you, I just wanted to ask why it doesn't work😁
basically just let each player take care of their own status
@woven arrow Even better
private void OnCollisionEnter2D(Collision2D collision)
{
UnityEngine.Debug.Log("coll");
if (collision.gameObject.CompareTag("Player"))
{
FaengerSwitch();
UnityEngine.Debug.Log("Switch!");
}
}
public void FaengerSwitch()
{
if (faenger) transform.position = new Vector3(5, 0, 0);
else transform.position = new Vector3(-5, 0, 0);
UnityEngine.Debug.Log(faenger);
faenger = !faenger;
UnityEngine.Debug.Log(faenger);
}
I've solved it like this now:
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Player"))
{
FaengerSwitch();
UnityEngine.Debug.Log("Switch!");
}
}
public void FaengerSwitch()
{
faenger = !faenger;
if (faenger)
{
gameObject.transform.position = new Vector3(5, 0, 0);
}
else
{
gameObject.transform.position = new Vector3(-5, 0, 0);
}
}
anyone?
Probably want to minimize the area where it could break
and give us more of an idea cause you've a lot of functionality on it already
probably in GetSelectedItem
What exactly breaks? And what does it mean for the tool to break? Where is it in the code?
The entire foundation of your system is messy to begin with. You're gonna keep getting into trouble for every feature you add. Some things to consider:
Why do you check in Update every frame if an item has been selected? Shouldn't each item slot be a button that then will call a method when clicked?
Why do you need to get the IEquippable and ResourceItem every frame? It would be better to cache those when you create the item. ItemHolder should probably be a script of it's own.
And also don't destroy the item each time you select a different one, instead change out the sprite/model.
have you done anything to isolate your problem? I see no evidence of debugging in your code
the slots in which tools break become unusable and deletes itself when selected
I question your update loop a bit as it feels like you shouldn't be foreaching over your inventory every frame or is there something im not understanding
well im trying to make minecraft like toolbar system
these 4 slots are broken and when i try to switch to them, item model disappears and so does the item inside slot
i have a small problem. I want to instantiate a button prefab. I wrote the script, added the component, added the prefab in component. When i start, the prefab isn't adding to object list.(the button should be added when the scene starts.)
buttons are UI elements which need to be parented to a canvas
also, why do you have 'GameObject Button;' instead of 'Button Button;'?
If you're following a tutorial I suggest going over it again. Inventories aren't the easiest and require quite a bit of logic to get just right.
i will change it, so i should make a canvas in my 1sthalf and than add buttons to it?
Is your inventory working without it
because make sure you've got that working first before the hotbar
yes it does but how would i select items
you should have in your script:
public Transform parent;
then when you spawn the button you can either add the parent inside the Instantiate() method or call:
clonedButton.transform.SetParent(parent);
and you assign your canvas (or a child of the canvas) to the 'parent' variable.
oh right minecraft doesn't have an inner inventory, then what inventory did you make? No wait, it does
thank you
So is this a toolbar or inventory
that's toolbar
and does your inventory work then
Ok, cool yeah
Ok, so since minecraft bar isn't type specific, you can pretty much design it how you did the inventory
Make another 'Inventory' of slots that will be your hotbar
it is already part of inventory
my problem is that slot becomes unusable when tool breaks
If your tool breaks you'd just set what ever was in that slot to null
foreach (Transform item in itemHolder)
{
ResourceItem resourceItem = item.GetComponent<ResourceItem>();
IEquippable tool = item.GetComponent<IEquippable>();
if (selectedItem != null && selectedItem == resourceItem.item)
{
if (!itemHolder.GetChild(selectedSlot).Equals(item))
{
item.gameObject.SetActive(false);
tool.Unequip();
}
equippedItem = itemHolder.GetChild(selectedSlot).gameObject;
equippedItem.SetActive(true);
tool.Equip(itemHolder);
}
else
{
item.gameObject.SetActive(false);
tool.Unequip();
}
}```
Where does the tool break. I see unequip and setactive(false)
if (durability <= 0 && toolObject.canBreak)
{
inventory.GetSelectedItem(true);
}
how can I put 2 particle systems on 1 object?
And activate them seperatly at different times
since the tool is not stackable and has count of 1, whole slot just disappears
which makes sense
Well, I'm going to assume the error is in that method and an error for stacking does sound possible
so I'd suggest start throwing debugs into it all because there's a lot going on in the script
put them on two children instead
Does it not let you? You can always just create children objects and child a system on each
guys i want to ask. I am running into a problem where I add the 2nd box collider as a trigger and adjust it accordingly but It does not trigger the Player In Range Bool. Anyone know this problem?
What does the code look like?
Most common cause is using OnCollisionEnter/Stay/Exit instead of OnTriggerEnter/Stay/Exit
like this
I couldn't tell you tbh, but if it's only needed to find the distance to the player and nothing else then using something like Vector3.distance between the two positions might work better than using triggers
i see thanks for the answer
by the looks of those errors by following some basic C# tutorials
Make sure to have your ide configured
well i have the c# extention downloaded
If I have a list, can I assign an individual bool value to every entry?
loop
foreach (bool this in list)
{
this =false;
}
I have a bunch of headers for my unity game
[Header("MovePlayer")]
public float origSpeed = 10;
float moveSpeed;
Vector2 moveInput;
[Header("Dash")]
public float dashSpeed;
public float dashCooldown;
public float dashTime;
bool canDash = true;
[Header("Sword")]
public GameObject rotation;
public GameObject attackRange;
bool canAttack = true;
bool attacking = false;
[Header("FirstAbility")]
bool canUseAbility = true;
public GameObject firstAbilityRange;
float firstAbilityCost = 33;
[Header("SecondAbility")]
public float secondAbilityCost = 33;
[Header("Mana")]
public float mana;
public float maxMana;
public Image manaBar;
public Color lightRed;
but for some reason just the [Header(FirstAbility)] isnt woorking
anyone know how to fix
thanks
you cant do that
or
do FOR loop
and List[i]=true or false
wait no I said it wrongly-
you cant modify the foreach variable
you need to use for loop to modify the list
foreach(type x in Xs){
x=other;//prohibited
}
for (int i = 0; i < liist.Count; i++)
{
liist[i]=false or true
}
typically, you tell us what is wrong with the code (along with the error) so we can help . . .
I meant that
When an entry from this list passes the if check, a bool variable linked to that specific entry is set to true-
what are you trying to do? what is happening instead?
each entry has their own bool? where?
cant understand
you mean there is a bool on the component (your script) that on the enemy or you want to store it somewhere
Right, sorry wait a minute
I want to create a bool, stored in this script, for each entry in the list-
create a bool list, finish
btw check if the count>=enemies.length whatever before you loop through the enemies
what do you mean by finish?
Hi ! This error is pissing me of, the project is completely new i just installed some package.
private List<bool> some_name=new();
why does the first ability header not there in inspector
[Header("MovePlayer")]
public float origSpeed = 10;
float moveSpeed;
Vector2 moveInput;
[Header("Dash")]
public float dashSpeed;
public float dashCooldown;
public float dashTime;
bool canDash = true;
[Header("Sword")]
public GameObject rotation;
public GameObject attackRange;
bool canAttack = true;
bool attacking = false;
[Header("FirstAbility")]
bool canUseAbility = true;
public GameObject firstAbilityRange;
float firstAbilityCost = 33;
[Header("SecondAbility")]
public float secondAbilityCost = 33;
[Header("Mana")]
public float mana;
public float maxMana;
public Image manaBar;
public Color lightRed;
can someone help me?
i want to make enemy shoot bullets in whichever direction player is, i tried few things but results are not the way i want.
if player dodge the bullet or change direction then bullets should keep moving in the same direction until it hit another object or cross boundary.
the most accurate result i got is with MoveTowards function but then bullet keep following player.
[Header("FirstAbility")]
bool canUseAbility = true;//default access modifier is private
public GameObject firstAbilityRange;
float firstAbilityCost = 33;
thank you soo much
Hello everyone! I'm experiencing an issue where new text appears on my screen whenever I open and close the crafting system, as well as the inventory system. This is demonstrated in the attached video. The scripts involved in this issue are the Selection Manager script, CraftingSystem, and InventorySystem.
https://gdl.space/ivojuvitiy.cs
https://gdl.space/odamedupab.cs
https://gdl.space/uparemikod.cs
Direction * Velocity * deltatime
rather velocity has direction ;p
so scratch that
so instead it would be speed * direction * deltatime
and just append to your position (bullet) every update
what does "=new" do?
in transform.translate?
Uh, you can just directly update the position
=new does nothing, in fact it's an error
=new() makes a new instance of the type
oh okay-
Ah, translate updates relative to its locality
i tried this and it works too but the problem is that the aim is very wrong
Maybe it has something to do with the interaction_info_UI but i cant figure it out..
when i use movetowards then the aim is perfect but then it keep following player and if i use position in start then it stops at that points
You sure you got your direction correct when you fire it?
for the above method
yes im sure
movetowards will always chase the target, but the other method will continue in the direction given
so if the aim is off, I'm going to assume something is wrong with the direction so I'd debug your methods
can you please write the code for me?
i spent hours but cant do it correctly
well, how do you get a direction?
i took the reference of the player object from scene then used a vector3 variable to get its position
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
Thanks
We'd need to know the errors. Your previous error stated that you've got an invalid expression.
#💻┃code-beginner message
I'd say take it to #📲┃ui-ux, but it seems like you're activating the gameobject so why not just get rid of it?
You can also normalize by using vector3.normalize such that:
Vector3 heading = (target.position - player.position).normalized;```
OKayy
so now you have a direction, give it a speed, and multiply it by deltatime (in update)
It has to do something with the code. I want to use this to show when i hover over objects to grab them. So i cant get rid of it
Thanks for helping 🙂
i really want to solve this
Well then you should only have the text enable when you IPointerEnter one of your slots
Unity documentation sucks but check this out if you plan on doing tooltips and/or drag and drop features:
https://onewheelstudio.com/blog/2022/4/15/input-event-handlers-or-adding-juice-the-easy-way
Need to add a little juice to your UI? Maybe your player needs to interact with scene objects? Or maybe you want to create a dynamic or customizable UI? This can feel hard or just plain confusing to add to your project. Not to mention a lot of the solutions out there are more complex than they need
i almost got everything working, now how would i filter this so it doesnt set 2 objects active, only one?
Item selectedItem = GetSelectedItem(false);
foreach (Transform item in itemHolder)
{
ResourceItem resourceItem = item.GetComponent<ResourceItem>();
IEquippable tool = item.GetComponent<IEquippable>();
if (selectedItem != null)
{
if (selectedItem == resourceItem.item)
{
item.gameObject.SetActive(false);
}
equippedItem = item.gameObject;
equippedItem.SetActive(true);
tool.Equip(itemHolder);
}
else
{
item.gameObject.SetActive(false);
tool.Unequip();
}
}
Hello! I want to ask what is the good collider for these characters? im currently using the polygon collider 2d
polygon is the best prob
also not a code question
oh mb what is the right channel to ask it?
which objects?
equipped items
probably #💻┃unity-talk if doesnt fit any channnel
im holding one but it sets two active
a prefab?
wha?
void SpawnNewItem(Item item, InventorySlot slot)
{
GameObject newItem = Instantiate(inventoryItemPrefab, slot.transform);
InventoryItem inventoryItem = newItem.GetComponent<InventoryItem>();
inventoryItem.InitializeItem(item);
GameObject newItemModel = Instantiate(item.model, itemHolder);
newItemModel.SetActive(false);
}
here
last lines
ok so ur making it twice?
Does anyone here actually use features like Steam login & Cloud Code Modules?
Been struggling with both for 3 days now, finally got most of it figured out but DAMN ... The docs are SO useless ...
Only know User/Email and cloud save sorry
whereas if i had like 999 rocks it would have only 1 game object in itemholder
this is more of #archived-unity-gaming-services question tho
oh there's a channel for that 😮
the instantiate looks sus
you'd have to debug. SpawnNewItem item correctly
there isn't something obvious im noticing yet
if im holding only 1 pickaxe in hotbar it should set active that pickaxe game object only
not 2
well what is the condion that activates 1 or 2
there probably isnt a solid check to ensure only 1 item is held
how many scripts is this whole system ?
send the relavent one in https://hatebin.com
thats a look ot scripts to look thru, dont u know which ones are more relevant . You've built it no?
yes this one is more relevant
Item selectedItem = GetSelectedItem(false);
foreach (Transform item in itemHolder)
{
ResourceItem resourceItem = item.GetComponent<ResourceItem>();
IEquippable tool = item.GetComponent<IEquippable>();
if (selectedItem != null && selectedItem == resourceItem.item)
{
equippedItem = item.gameObject;
equippedItem.SetActive(true);
tool.Equip(itemHolder);
}
else
{
item.gameObject.SetActive(false);
tool.Unequip();
}
}
its a switch between item models
like from pickaxe to rock
you probbaly wantto break then once one of the items is set or something
this whole system already looks frail
how do you set selectedItem
public Item GetSelectedItem(bool use)
{
InventorySlot slot = hotbarSlots[selectedSlot];
InventoryItem itemInSlot = slot.GetComponentInChildren<InventoryItem>();
if (itemInSlot != null)
{
Item item = itemInSlot.item;
if (use)
{
itemInSlot.count--;
if (itemInSlot.count <= 0)
{
Destroy(itemInSlot.gameObject);
Destroy(equippedItem);
equippedItem = null;
}
else
{
itemInSlot.RefreshCount();
}
}
return item;
}
return null;
}
tried that still doesnt work
i think its to do with how my enemy moves
I would put some Line Breaks and see whats happening when you select the axe
wdym?
checkmark is a rock
if (selectedItem != null)
{
equippedItem = item.gameObject;
equippedItem.SetActive(true);
tool.Equip(itemHolder);
break;
}
```this is all i did
dear Mao, can you look into this script? i think here is the error of my new text problem.
You're setting active to your text a few places so I suggest figuring out why if it's the problem
yes but still can't figure out why it is activating when i open and close the inventory screen / crafting screen.
I suggest adding Debug.Log to each place you activate your text then maybe youll figure out where
Hi ! I don't see my function I just created, why that ?
which script
method has to be public
Yu have 4 console errors ur ignoring..
This is the console error
the top one is clearly relevant
also google how to remove the Collab warning
you have to disable it in project settings
Hey all, I'm not sure how to search for my problem but here's the gist:
I have two types of ScriptableObjects, WeaponData and RuneData, both have the same attribute of itemType which defines what kind of Item they are. I want to be able to have one field in the inspector to put either ScriptableObject in, and for it to assign attributes based on the itemType in a script called Item.
How do I generalise the "public WeaponData weapon" and "public RuneData rune" into one "public ScriptableObject item"? is that possible? is there a better way maybe?
Ok i have disabled it
have the same code as him but still manage to have error
One big difference, he saved his code and you didn't
this says different
if your error wasntt highlighting in ur editor
!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
Please stop thinking i am a retard
if i say that i saved it means i saved
To fix the issue, I updated the Update method in the SelectionManager script. The solution involved resetting the text of interaction_text to an empty string whenever no interactable object is targeted. This ensures that the item name is cleared from the UI when the player is not focusing on any interactable objects. The code now checks for the absence of a target both when the raycast hits something and when it doesn't, ensuring that the item name is properly reset in all scenarios.
if you had saved then that little * next to the file name would not be there
no need for ableist slurs
that screen with the * is the screen of the youtuber, my screen is the one with no *
so ? i didn't saved ?
then, at a guess he is not finished entering code
yes he finished
Make sure to configure your ide. It is necessary to acquire help on the server.
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 137
Number of times it was exactly like the tutorial: 4
Number of times the code literally did not exist: 1
2022-07-19 to 2023-11-26
bro so help me instead of wasting time writing useless stuff
you have literally already been told what your problem is
bro can't read xD
i'm french and i have a bad english, you guys just pissing me of rn i want to break my desk
calmdown edgy boi
you just said """"you haven't register"""""" and """"""he haven't finished coding"""""""""
mate you gotta configure your IDE
no more help for you until you prove you have a configured ide
You've been told exactly the issue throughout this entire conversation and linked to it again.
Configure your !IDE and you it literally will not let you make spelling errors that break your code
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
ok
Hello, I am working on multiplayer tank game, and I have this code for despawning the tankObject and spawning some particles when it dies. If a client calls the DestroyTankServerRpc() it all works fine but if the host calls it I get
[Netcode] Deferred messages were received for a trigger of type OnSpawn with key 30, but that trigger was not received within within 1 second(s). UnityEngine.Debug:LogWarning I am not sure what causes the warning
!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.
aight here is the code, sorry
https://paste.ofcode.org/mNAmQPXrFw7Uf8ysc2PWbQ
📃 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.
how do i set a objects velocity to 0
rigibody.velocity = Vector3.zero
and anuglarVelocity if you also want to set it to 0
rigidbody.velocity = Vector3.zero;
rigidbody.angularVelocity = Vector3.zero;
ok thanks
In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour tho
well im trying to have a thing launch the enemys but since they are moving they dont get pushed back far unless i set theforce amount super high and then they just get launched super high up
so if i set their velocity to 0 right before it should be better i think
A physical object would usually not stop dead suddenly
if you want realistic behaviour
imagine car going 50mp/h and in 0.01s it just suddenly stops
still doesnt work they barely move
🤷
any ideas how to make it work better
we cant help without any context
targetRb.AddForce(launchDirection.normalized * launchForce, ForceMode2D.Impulse);
thats the code to launch them
Are you modifying velocity anywhere else
That will override addforce
Show ALL the code so we can have more context
Vector2 movement = direction * moveSpeed;
movement.y = rb.velocity.y;
rb.velocity = movement;
thats the part where the enemy moves
so what should i be using
either JUST use AddForce to change thier velocity, OR set the velocity directly
well velocity takes a vector3
you know how a vector2/3 works right ?
direction.y=0; AddForce(direction*force); would apply NO force in Y axis
not really
err Y, sorry
well something you should get familiar with if you're doing unity
its just 2 or 3 floats
depending if its Vector2 or Vector3
X,Y,Z
so since im making a 2d game shouldnt i always use vector2
Unity is a 3D engine
both work the same
if you type vector3 into a vector2 Unity doesn't care
it just put 0s at Z
you just can't do V2 + V3
afraid best answer we can give to this is "probably".. are you rigidboies Rigidbody2D?
either way if you only want the X axis then that will always be the first number
yeah
Then I'd recommend you go with Vector2, just to keep it consistent.
yes. but note terminology- you ACTIVATE/DEACTIVE gameobject, and enable/disable components ON an object
alright thanks
how would i have it edit a variable for the other object
basically it would make it so the other object cant run
You reference it
wait actually cant i just freeze the x instead
what is it ur trying to do? how about start with that
im trying to make it stop moving right before you luanch them so it actually launches them and they dont just push tyhrough it
whos them? I dont know ur setup
so bascially i have a wave of enemies attacxking the player the player has a move that repels enemies but it moves them like a inch rn i want them to get launched furthur
if you want AddForce to affect them you have to temporarly disable any part of the script with .velocity =
I would use a bool for .velocity like (isStunned ) or w.e , and a coroutine to push AddForce
How do I add AI to my PONG second paddle?
looks like you got AI already
I guess a related question is what's a good resource for it?
No it's me controlling it
Ohh
What I do is make it roughly follow the Y of the ball
and sometimes Add Random Speed accelerations for fake "dumbing down"
i'd calculate the angle or direction of the ball and move the paddle accordingly
Eg if ball is approaching start lining yourself up, and depending on difficulty add more and more imprecision
Hmm maybe AI is a bit outside my comfort zone... can you recommend a different modification? I'm still learning but I want to mod the game
Definitely looks solid to me
literally rn. this should give you basic start ```cs
[SerializeField] private Rigidbody rb;
[SerializeField] private Ball ball;
private void FixedUpdate()
{
var dir = ball.transform.position - transform.position;
dir.Normalize();
rb.velocity = new Vector3(0, dir.y * 7, 0) ;
}```
I have anotherone with the AI I described b4 with random movespeed
anyone know why the animation still plays?
private IEnumerator BounceTowardPlayer()
{
while (true)
{
yield return new WaitForSeconds(1.5f);
if (isGrounded)
{
if (!IsStunned)
{
animator.SetTrigger("Jump");
yield return new WaitForSeconds(0.6f);
Jump();
}
}
}
}
wdym "still plays"
like they are stunned but it still plays the animation
it also depends how many times you actually called this routine
and how did you check the condition isStunned actually false
because i also have that for if they can move and they dont move but the animation plays
I dont understand
Put a Debug.Log inside the trigger code part then
verify thats not the source of issue
if you keep seeing debug then its running
huh so i stop seing the debug
i found the issue
when unity crashed yesterday and reset stuff i forgot to remake the animator
now it works lol
What's the equivalent of the walk of shame in the unity development community
Because I've been coding with chatgpt and now I'm scared to ask for help fixing my nonsense script
that'd be it..
knew it
I am trying to create a UI element that is basically an editable to-do list. I was going to just use unicode checkboxes but it didn't want to do that, so I went ahead and made my sprites for it, set those up as prefabs. The checkboxes spawn in with the list entries. when I try to delete list entries with right click, the corresponding checkboxes are never destroyed.
https://gdl.space/raw/xixeyadago
puppy tax
ChatGPT and posting off topic, you're not making friends here
ur best bet is to pretend u didnt say it was chat gpt code.. and just ask like u woulda had u wrote it on ur own..
and make sure u go and fault chatgpt, let him know the trouble he's caused by giving u code snippets w/o explaining to u why they do what they do
I mean I went through that song and dance in the 2000's on web forums. The last person I want to impress is someone that's going to whine about a dog photo
So far this is going just about as expected
Anyone know why Content Size Fitter on TMP_Text isn't updating when adding space? " "
As much as I love trying to shame an AI, we all know I'm the idiot here, so I'd better not
not code related question
I only see a single class here. I recommend you split your code up so it is easier to work with. TaskDisplay should be a class. TaskDisplayController should be a class handling the spawning of TaskDisplays.
here my health as TextMeshPro
and in my gameManager i have
// UI prefabs ===============================================
public TextMeshPro scoreText;
public TextMeshPro healthText;
but i cant drag and drop the Health object in the inspector? im not sure why this is not working
Do TextMeshProUGUI
u need ^ or TMP_Text
legends, thanks
should I use array.Length or array.Count? it throws an error for Count and it can't find Length..
Arrays have Length, they don't have Count
Assuming you mean "array" as something like GameObject[]
yeah thats exactly what I wrote in my code
Make sure you wrote the name correctly, with correct capitalization
length is not the same as Length for example
gives me "Object reference not set to an instance of an object Inventory.isFull() with this code:
wait
This is not configured
!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
Please do that, you'll get errors in the code, as well as suggestions for names as you type
Hey guys
Sorry in advance for my poor knowledge and english (non native english speaker here) but i just started making a game from scratch and i came across with this problem, so im not really into coordinates cuz im getting started in programming so i used a code from a tutorial i saw on youtube, for context the MC is set to 45 X Rotation, the problem is when i press the "S" Key he just goes floating to the space lol
So i was expecting i could get some help
this error implies your items array has not been instantiated: e.g. items = new GameObject[10];
is that how I instantiate it?
can you provide some more detail about what you mean "floating to the space"?
Yes your code will move the character when you press those buttons, that's what you wrote it to do
that is just an example, but yes, it's an example of how to ionstantiate an array of 10 GameObjects. But I don't know if you actually need 10, or when woudld be an appropriate place for you to do that.
It's how you initialize it. Just to clarify
^ no
my examle is how to INSTANTITE is
no it is not xd
ok
items = new GameObject[10]; this is initialization
You don't create any gameobjects with what you did glurth
You just initialize an array
I'm not good with terms, can I substitute a number with an int when declaring the size?
yes
I instantiated an array. perhaps you mean rthe gameobjects?
does that have to go in the Start function? having a hard time wrapping my head around what goes where
You initialize an array, you instantiate gameobjects
You cannot instantiate an array
sure, can i send videos here btw?
ig it would more clear if i just show
well you instantiate both but you UnityEngine.Object.Instantiate the GameObjects whereas you use new to instantiate the array
no, intitalizing an array is fi;lling it with values.
Is it a 2d game or a 3d game? Why is MC set to 45°? Show a screenshot maybe
no you didint instantiated the array
Well, i may be wrong I guess 🤷♂️
I trust praetor
Instatiate: allocate memory for an object, create a refernce to it. Initialze: fill with a specific value
Its a 3D game using the 2D Sprite package, the MC is set to 45 cause im trying to replicate the Paper Mario and Dont Starve aesthetic
how can i make an objects transform.position match the speed of a texture offset on a quaternion model?
I'm making a 2d endless runner game, where the background is just a 3d model with a texture that gets a constant offset to make the impression that everything is moving, parallax and all that. But i just can't find a way to sync the obstacle's speed to match the background offset speed, is there a way for me to do that?
maybe add the sprite as a child and rotate that instead of the actual gameObject
@wintry quarry I trust that guy too 😉
What you say makes sense, and looking it up confirms it.
I learned something new and I appreciate you sticking with it!
wdym as a child?
im really new to gamedev and programming in general so i dont get it sorry
parent is a root object, the objects (parented) to it are children.. they follow around that object (scale, position, etc)
oh ok like a "chain" then
got it
I'm trying to add a smooth camera lookaround. This works, but it jumps from position to position and only seems to know four directions for some reason:
private const float LEFT = -2.12f, RIGHT = 2.12f, TOP = 1.16f, BOTTOM = -1.13f;
private Camera _camera;
private void Start()
{
_camera = GetComponent<Camera>();
}
// Update is called once per frame
void Update()
{
var mousePosition = Mouse.current.position.ReadValue();
var inWorldPosition = _camera.ScreenToWorldPoint(mousePosition);
transform.position = new Vector3(
Math.Clamp(inWorldPosition.x, LEFT, RIGHT),
Math.Clamp(inWorldPosition.y, BOTTOM, TOP),
-10
);
}
im confused.. a look would be a camera's rotation..
what i see here is you modifying the Transforms position.. (moving the camera around) vs rotating the camera around
It's top down 2D
Where LEFT is the limit to the left side, right to the right and so on
oh okay so u do want the camera to move around
Exactly, based on the cursor position
Ohhh I found the error
It should be ScreenToViewportPoint and not ScreenToWorldPoint
Nice!
that worked like a charm thanks! : )
in unity, how do i see multiple scenes in the editor? i can only see the one im currently editing
You drag in the other scene to the hierarchy
That will additively load both
thx
!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.
Anyone know any good guides or tutorials for making a simple dungeon/room generator in 2d?
https://paste.myst.rs/ihhf47ye how do i fix this
a powerful website for storing and sharing text and code snippets. completely free and open source.
fix what
for post proceesing
wdym? What's wrong with it? Isn't this Unity's code from the PPV2 package? https://docs.unity3d.com/Packages/com.unity.postprocessing@2.0/api/UnityEngine.Rendering.PostProcessing.PostProcessLayer.html
This must be the least amount of context I have seen in a question
it's either a bug in the package or you misconfigured your scene / postprocessing settings somehow
In the former case - make sure you have the most up to date version oft he package and/or submit a bug report
In the latter case - fix your settings
prevent me from running my game i think
that's a runtime error
wanna see my post processing settings
Hey, idk is it good channel, but I have a question regarding canvas. I want to place background image in Canvas(so it doesn't move) but is there a way to move it behind all the other sprites?
#💻┃unity-talk or #📲┃ui-ux
This is a code channel
Look into sorting layers
ok
hey friends. i'm trying to designate a random gameobject(specifically its transform) from a list made by objects that are within a overlapcircleall as a "chosen" object, but im unable to find the right syntax to get this working
OverlapCircle gets a collider. You should be able to do allEnemys[randomIndex].transform
Or allEnemys[randomIndex].gameObject.transform
Can't remember if you can directly get the transform from a collider
oh you are brilliant, i think this has worked
Is the Debug.log ran on unscaled time?
Debug.Log has nothing to do with time
like, if i run a Debug.log on my update, will the log stop if time stops?
Update runs every frame
Regardless of time scale
Changing time scale doesn't affect framerate
Good to understand that if it did stop, it would be because Update wasn't running, not because of anything related to Debug.Log
alright
Yes, this question has nothing to do with Debug.Log it's really about time scale and Update
but another question
i made these variables and debugs to check if time was accelerating(the game getting harder), and the debugs work and all of that but the accelerated one seems to be passing time slower than the unscaled one.
"Tempo puro" = unscaled time
"Tempo acelerado" = accelerated time
Did you change the timescale?
I dont know what you're specifically trying to do with that, but you shouldnt do it like this.
Your time.deltaTime depends on the time scale, which is why unscaled time exists.
like the accelerated one counts faster or something
As time scale is higher, deltaTime will be lower. FixedUpdate for example will get called more frequently, resulting in fixedDeltaTime to be lower. Unscaled delta time will stay the same, as its name suggests, it's not affected by time scale
I'm doing it like this so that i don't need to make a specific speed that scales in a different way for every object that is supposed to accelerate over time
oh, so there isn't something wrong with the code itself but with how deltaTime works, right?
the time in between gets faster
Well first thing, you are increasing the timescale a small amount per frame. So someone on very high fps would have different gameplay from someone on low fps
so i multiply it by deltaTime?
unscaled i would say for this...
like i do that so that things won't work faster in high fps, should i do that for timeScale?
I'd still say you shouldnt be using timescale like this at all, itd make more sense to just have a separate object which exists as a scaling factor in your game.
so i should create an object that scales and then multiply everything that should scaled by it?
It depends what you are scaling, I'm unsure if you described what this is really for
The game is like a 2d subway surfers, so i need everything to accelerate over time
I don't really think subway surfers accelerates with time scale
the movement speed of the player just increases
cause its 3d probably
what difference does 2d vs 3d make
in 2d i'm doing a texture offset thingy to make the background seem like its moving
and the player doesn't really move
you can just increase the speed of that movement then
again no need for time scale
Then wouldnt you only need to scale the move speed of things? For example you wouldnt need to speed up every single animation and change how fast fixed update runs
Note for example in this video:
https://www.youtube.com/watch?v=7ghSziUQnhs
- The falling snow speed does not increase
- The train movement speed does not increase
- the spinning speed of the coins does not increase.
The only thing increasing is the player movement speed
i mean... i will be scaling a couple of animations, but i think it can be done with the scaling object that you suggested
Yeah, 1400 lines of code and the question is "how do I fix this" 😆
I'm trying to create a temporary buff for my player when an item i picked up.
This is the code I'm using for my item:
using UnityEngine;
public class AttackPotion : MonoBehaviour
{
[SerializeField] int bonusDamage;
[SerializeField] float duration;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player"))
{
if (PlayerStats.Instance.bonusDamage <= 0)
{
StartCoroutine(PlayerStats.Instance.ApplyBonusDamage(bonusDamage, duration));
}
else
{
PlayerStats.Instance.potionGreen++;
}
AudioEffectsManager.Instance.PlayPotionSound();
CollectableUI.Instance.UpdatePotionGreenText();
Destroy(gameObject);
}
}
}```
THe Coroutine ApplyBonusDamage() looks like this:
```cs
public IEnumerator ApplyBonusDamage(int damage, float duration)
{
Debug.Log("Starting buff!");
bonusDamage = damage;
Debug.Log("bonusDamage set to: " + bonusDamage);
yield return new WaitForSeconds(duration);
bonusDamage = 0;
Debug.Log("bonusDamage reset to: " + bonusDamage);
Debug.Log("Ending buff!");
}```
Th UI is updated and the bonudDamage is applied correctly. THe issue I'm having is that the bonusDamage is not set to 0 when duration seconds have passed (in the coroutine ApplyBonusDamage(). When I check the Debug-Log() output, I can see that onlt the ones before the WaitForSeconds() have been written to the concole.
!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.
Coroutines are tied to the lifespan of the object its ran from. so if you destroy the object before the duration has finished. it's not going to get set back to zero.
Aha, I did not know that. You learn something new every day. 🙂
So, if I remove the Destroy() form the OnTriggerEnter2D() and pass the gameObject into the Coroutine, I can Destroy the object after the bonusDamage is set to zero?
and on the backend of this. you should never start a coroutine like this on another object
instead, make a function that returns void, and start the coroutine in that. (the same script that has the coroutine)
and then in the class you need to start it: PlayerStats.Instance.ApplyBonusDamage(stuff);
Absolutely correct
Changed it around a bit and it now looks like this instead:
public void BonusDamage(int damage, float duration)
{
StartCoroutine(ApplyBonusDamage(damage, duration));
}
public IEnumerator ApplyBonusDamage(int damage, float duration)
{
bonusDamage = damage;
yield return new WaitForSeconds(duration);
bonusDamage = 0;
}
Works like a charm. 🙂 Thanks for the quick help.
I'm trying to set up bools for walking, crouch walking and running. Should i base them off of input or player velocity?
Entirely your decision; your game. I would think about what makes sense though...
To me, these sound like all different states/input. Walk state, crouch state, run state, etc.
I mean, checking if the player is walking/crouchwalking/running. currently I'm having issues with input.
Can you share it?
And what do you mean "issues with input"?
{
StartCoroutine(isCrouch());
}
if(KBMinUse && KBMinUse && Input.GetAxis("Horizontal") == 0 || Input.GetAxis("Vertical") == 0)
{
isCrouchWalking = false;
StopCoroutine(isCrouch());
}```
if the coroutine is going for the 1 second, then the playing is crouchwalking.
Well your || Input.GetAxis("Vertical") != 0 could make the condition fire. You realize right?
Really? I'm checking to see if the key is being pressed.
I assume you want this only to fire when the player isCrouched right?
I want it to fire, when the player is crouched and is moving also.
First part you're checking if the player is crouched, kb in use, and if horizontal input is not 0. Second half of it you're asking it to fire if vertical is not 0.
So whether player is in crouch or not, as long as vertical is not 0, fire.
It only works when both A and W, or S and D, is being clicked at the same time, it wont work if any of the keys are being pressed.
Apologies, I think your conditions are correct actually. you have the right order of operations. Let's go back, what is the issue you're experiencing?
The isCrouchWalking bool is true when both axises are being changed, but if just one is being changed, the bool flickers or doesn't change at all.
Basically if i click A and W, or S and D.
wait dude im tripping and so out of it today lol. I am correct (or going crazy), you need to repeat your conditions, otherwise you'll start the couroutine anytime that vertical is not 0. Which you dont want, you want the player to be crouched.
But i think you have another issue, let me read this
Can you share the full script?
Are you sure, it's long, and pretty messy?
all good
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
damn you werent lying
lmao, i'm not the best at writing neat code.
It's not about "neat" it's just that you're going at it the wrong way really. All these conditions and bools everywhere are just a cause for pain and confusion. Good for learning and starting small, but it's not manageable for larger projects. Give me a min..
Most components have a .enabled property so use that
why cant i access functions from my script??
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using Unity.VisualScripting;
public class UIController : MonoBehaviour
{
public TextMeshProUGUI countdown;
public void OnWaveEnd()
{
Debug.Log("Wave ended!");
StartCoroutine(Countdown());
}
IEnumerator Countdown()
{
countdown.enabled = true;
countdown.text = "5";
yield return new WaitForSeconds(1f);
countdown.text = "4";
yield return new WaitForSeconds(1f);
countdown.text = "3";
yield return new WaitForSeconds(1f);
countdown.text = "2";
yield return new WaitForSeconds(1f);
countdown.text = "1";
yield return new WaitForSeconds(1f);
countdown.enabled = false;
}
}
i have them
Drag in a UIController object from the scene, not a script file
thanks
you can replace that with a for loop btw to make it less cluttered
for (int i = 5; i > 0; i--)
{
yield return new WaitForSeconds(1f);
countdown.text = i.ToString();
}```
Im having an issue where whenever I create an object its extremely small
Does it use a model imported from blender perhaps?
The basic primitives are 1m
I have to scale it up to around 50 for it to be a normal size
So you're probably just far away ...
I cant even zoom in to it
The camera literally cannot zoom in more
Click on it and press F
You can select an object and hit F while hovering the cursor on scene view
This isn't a coding issue either.
Is there a way to check how long it took for a function to run? I have top watch in my function in nanoseconds but there's no seconds shown
I'd expect the performance profiler to have that info. Otherwise, you could use the (less accurate) stopwatch for an estimate.
Cache the start time and subtract that from the end time
Or use a profiler
For quick measuring I usuall go with stopwatch.Elapsed.TotalMilliseconds
I'm using a UnityEvent like so
playerHandService.OnCardDrawn.AddListener(RenderNewCard);
This calls the method when a new card is drawn:
private void RenderNewCard([NotNull] Card cardEntity)
{
var newCardViewContainer = Instantiate(_cardViewContainerPrefab, transform);
_drawOffset++; // <-------- THIS IS THE ISSUE
StartCoroutine(CreateCardAfterTime(newCardViewContainer, cardEntity));
DecreaseSpacing();
}
private IEnumerator CreateCardAfterTime([NotNull] CardInHandContainer container, [NotNull] Card cardEntity)
{
// Guarantee to wait one frame
yield return null;
// Now create a slight draw offset
yield return new WaitForSeconds(0.1f * _drawOffset);
container.CreateChild(cardEntity, this);
}
What I intend to do is to use an offset as an integer that is incremented each time a card is rendered. This offset then increases the WaitForSeconds, which is supposed to create a typical "draw" effect. However, running this, all cards wait for the maximum offset of 5 * 0.1f = 0.5f and then render at the same time. Is this something about UnityEvents that I don't understand?
Pass drawOffset as a parameter into the coroutine instead of using a variable in the class which will be shared in each coroutine
Ok I will try
Hey everyone
Does anyone know how to achieve wall jumping?
The issue is, I'm able to make the 2D box jump from one wall to another back and forth
But I want my character to be able to jump along the same wall if the left arrow is held
I tried with trial and error
But it doesn't seem to be doing much
Brilliant, thank you that worked! Could you tell me why? :)
When you do _drawOffset ++, every coroutine uses that same _drawOffset so they all end up using 5 or whatever your max value is
Using a local variable is key here
For example, your first coroutine starts, and after it has waited that one frame, _drawOffset was already changed to 5
So _drawOffset++; is executed five times before at least one Couroutine is started by unity, that's the issue?
Well the coroutine does start immediately but you have yield return null which causes the one frame delay
And during that delay all coroutines have started and _drawOffset has already reached 5
Make sense?
Ohhh yes! Totally, thanks for explaining! :)
What's the reason for yield return null; here btw? Is it because some UI didn't update in correct order?
If that's the case, you can try yield return new WaitForEndOfFrame() instead, which eliminates the frame delay but usually fixes that kinda stuff
Yes because of UI bugs. Ok I'll try!
i am removing the post procesing to see if it help me
That's pretty random
i remove the post processing from my game but i got ullReferenceException: Object reference not set to an instance of an object
UnityEngine.Rendering.PostProcessing.AmbientOcclusion.IsEnabledAndSupported (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/Effects/AmbientOcclusion.cs:183)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetLegacyCameraFlags (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:816)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.SetupContext (UnityEngine.Rendering.PostProcessing.PostProcessRenderContext context) (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:911)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.BuildCommandBuffers () (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:558)
UnityEngine.Rendering.PostProcessing.PostProcessLayer.OnPreCull () (at Library/PackageCache/com.unity.postprocessing@3.2.2/PostProcessing/Runtime/PostProcessLayer.cs:487)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)
i think i have remove it from the package manager
Yes
I want to make it softer
More of an #🏃┃animation question
uh sorry
I love you all guys, I don't know what I would do without all of you ❤️
ejem sorry
Is this notice about no MonoBehaviour scripts OK? I'm not using MB but I'm not sure if this is simply a notice or something that Unity isn't happy about
it's not ok.
Fix all compile errors and make sure the filename matches the class name
you also forgot : MonoBehaviour
I'm not using it
The app builds fine
if it's not suppsoed to be a MonoBehaviour then it's fine
that's all the message is saying - there is no MonoBehaviour in the file
I mentioned here, just making sure that it's not some fatal error or something
Hey guys i have a question .I have a script which compares the tag of my player and checks if it collides with an object, when colliding it should activate the canvas to put on a screamer. but it does not work. i am not sure what im doing wrong.
"doesn't work" is very vague.
You need to start debugging
adding log statements to your code is the first step.
this will tell us which parts of the code are running or not
I am using the same method for others screamers and they are working.
Thats why i am not debugging.
You have to debug
debugging is the only way to find the answer for sure
otherwise you are just guessing
don't think you can skip it for XYZ reason
i think i already know what the problem is.
you will always find the answer fastest by debugging systematically
without even checking. i think i forgot to put "Is Trigger" 💀
thats weird, not sure why but that specific object was created without a box collider.
even tho it was made out of a box.
It only has a box collider by default if you create it with GameObject > 3D Object > Cube
'WorldSaveGameManager' does not contain a definition for 'GetWorldSceneIndex'
The code in WorldSaveGameManager:
public int GetWorldSceneIndex()
{
return.worldSceneIndex;
}
Show the code for both scripts and show the full error message including filename and line number
Assets\Scripts\PlayerInputManager.cs(35,67): error CS1061: 'WorldSaveGameManager' does not contain a definition for 'GetWorldSceneIndex' and no accessible extension method 'GetWorldSceneIndex' accepting a first argument of type 'WorldSaveGameManager' could be found (are you missing a using directive or an assembly reference?)
if (newScene.buildIndex == WorldSaveGameManager.Singleton.GetWorldSceneIndex()
if this is the actual code: return.worldSceneIndex; then WorldSaveGameManager itself has a syntax error in it
because that is not valid C#
Do you know what the correct code to do that is
unsure
following a tutorial but thats not even what he typed
All errors gone thank you
How do I save a large array to a json file?
use a JSON serializer
I know I'm meant to use jsonserializer but I can't find docs
Never mind I found it, sorry
either UNity's JSONUtility https://docs.unity3d.com/ScriptReference/JsonUtility.html
or Netwonsoft JSON https://www.newtonsoft.com/json/help/html/serializingjson.htm
Also, how can I find out which version of .NET my Unity editor is using?
It's Unity version 2022.3 but I'm not sure which version it uses, Googling just gives .NET Standard 2.1 which isn't what I'm looking for
What are you looking for
Do I have to change this?
to do what?
I just want to know which one to select here
What are you trying to accomplish with this info
don't use this
this is for general .NET
you're in unity
Use one of these
I see, and Unity uses Standard?
Yeah I was planning on it, just seeing what Microsoft was suggesting too. Thanks.
what does multiplying something by Time.deltaTime really do? I mean i know that if i multiply something by it it will no longer be linked to the fps, but why is that?
imagine if your numbers actually had units
position in meters. acceleration in meters per second squared, etc.
If someone's computer lags and there is a 1-second gap between frames. Let's say your player moves 1cm for every millisecond that a key is pressed down. For that frozen period, the player will have moved very far.
Multiplying by deltatime ensures that that doens't happen
Time.deltaTime is the time that has elapsed in seconds within the last frame
provides consistency
through diff fps
not really, no
ohhh
so, should i put it everywhere that has an operation that is dependent on frames for a smoother deal?
if I want my character to move at 5 meters/second, and I am writing his position within a frame, you want to advance it by 5 meters per second, not 5 meters per frame
you need to do: position += velocity * Time.deltaTime
because Time.deltaTime is the amount of time in seconds elapsed in the last frame
It depends on how the operation works.
Moving a transform yes, adding force no
the reason all these explanations aren’t quite right is; if you did this in FixedUpdate, the calculation should become framerrate independent (mostly). But the calculation is incorrect
so this ain't right? (it's a prefab gathering things from another's objects code, that's why its a bit redundant)
what's FixedUpdate?
FixedUpdate runs at fixed time intervals
That is moving the transform..
But you do duplicate it. You only want the lower deltaTime
alright
imagine units on your numbers
what?
so if i'm using FixedUpdate i don't need to use Time.deltaTime?
no yeah i got that
from Unity's mouth
It is much more common to want your in-game objects to move at steady and predictable speeds regardless of the frame rate. The solution is to scale the amount of the movement each frame by the amount of time elapsed each frame, which you can read from the Time.deltaTime property:
https://docs.unity3d.com/Manual/TimeFrameManagement.html
steady and predictable speeds of the frame rate
thats what exactly i said
if velocidad has units of m/s. Then you just made velocidadjuste have units of m/s^2
which is wrong
velocity doesn’t have units of m/s^2
It's the opposite really. Multiplying it by deltaTime makes it move very far, because a lot of time passed, so it makes sense
Otherwise you would move the same amount per frame regardless of the frame taking 0.01 seconds or 1 second
alright so only one time.deltaTime, which is in the transform, i got that. but what about the FixedUpdate?
your simulation advances by Time.deltaTime each frame. If you want to define a velocity in units/second, and convert that to a position within a frame, then you NEED to use deltaTime as the conversion factor to know how much time has passed.
that might change the way i'm doing my whole code
and that isn’t to make it consistent. it’s because it is what makes it correct
if you DONT multiply by deltaTime, then you successfully defined your velocity in units/frame.
steady and predictable
sounds like consitent to me 🤷♂️
and if you want to define your velocity as units/frame, that’s cool. but that probably isn’t what you thought you were doing, and is therefore just wrong
this is not correct. If I don’t multiply by deltaTime, it is extremely consistent. Consistent as a velocity in units/frame.
You sometimes still do. deltaTime will be converted automatically to fixedDeltaTime though
framerate can change, but that velocity is still units/frame. Consistent, but wrong
that makes no sense
what is "sometimes"?
I think you both mean the same thing with just different wording of opposite things
Consistent across devices/framerates
Consistent per frame
Or "constant" per frame
I think I just made it even more confusing tbh
let’s say I serialize a field for velocity, and the tooltip says “how fast we move over time.” If you don’t multiply by deltaTime, then it is a velocity in units/frame, which contradicts what the tooltip says. Because we aren’t advancing over time, but over frames.
I just quoted the Unity Docs 🤷♂️ Ill take that explanation over any lol
How can you find compiler errors
could i remove the deltatime if i used "void FixedUpdate()"?
i usually just double click on them and it takes me to the line of the error
your IDE and unity will tell you about it. is there a specific issue you're having
because your units are not correct
Lets say you move something manually with rigidbody.MovePosition you want to use deltaTime/fixedDeltaTime.
But when adding forces, you don't want to do that since it's already used with ForceMode.Force and ForceMode.Acceleration
just check that your units are correct, and you will know exactly what is going wrong
!vscode
No. You would use it in exactly the same circumstances as in Update
units are how I could immediately see that the first line is wrong
so FixedUpdate is just if i want something that is not linked to the frame updates, but is also just running in it's own time?
i gtg now, but if you don’t respect units, anything physics-related will make your life miserable.
FixedUpdate is better for moving physics objects
No, not necessarily
FixedUpdate for physics
so if i have something that is moving, i should put it into FixedUpdate
or has a rigidbody
no thats not what we said lol
rigidbody is physics isn't it
yea
If you are moving it via physics.
Moving a transform is not
alright
best look at the docs to get the full details
never used anything physics related just transform until now
translation will never give you accurate collisions
but thanks for the help guys
wdym
if i use transform.translation the collision wont work
when you use Translate you're essentially teleporting
Moving via transform will not notify the physics that the object moves
So collisions will be mostly ignored
Just weird glitchiness all around
Colliders are part of the physics
so they prefer physics movement/ timestep
It CAN work if they are slow enough. But EASILY get messed up in many cases
maybe you're moving too slow to notice
but if my object doesn't have a rigidbody its still ok to use transform for as long as they aren't going a Mach God speed
I still wouldn't take the chance
for any collision
you don't want your players to experience a bad time for inaccurate collisions
my game has like one collision per game which will be the game over, can it still be messed up?
trigger
not collision
the collision part is made with a rigidbody
triggers colliders are part of physics btw
as long as 1 rigidbody is there between the trigger/collision
Your flipX is false for greater AND less than 0
Oh wait
You do flipX in four spots
Maybe just remove the top two?
ill try that
same result
alright so I have it fixed but the rest position after going to the right remains looking left
After you fix that, move the rb.MovePosition line to FixedUpdate instead. That's where you should move rigidbodies, not Update
Why did you change the bottom two when I said remove the top two?
It showed the same result like the first one I sent
Well, setting them both to false is very wrong. So change it back
Your video's behaviour doesn't match the code though... Is something else flipping it too?
Change it to what Aethenosity suggested first
The second if stuff is done after animation states - they aren't doing anything.
But maybe I'm wrong 
In the console or your IDE if you're using one
What's an sr? I'm assuming some sort of renderer..
console
Sprite Renderer
In your editor. At the bottom. You have two tabs, one that shows all your folders and files and Assets, the other tab called Console.
is this what you mean?
whoops I did something wrong