#💻┃code-beginner
1 messages · Page 523 of 1
so the base type is?
How do I use foreach for gameobjects though?
instead of group Group
you use the base type Group
Fixed it, thanks
anyone knowledgeable in animation states?
do not cross post also read this !ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
hi, im making a top down game similar to that of undertale. how would i go on about making a room system/loading rooms?
guys how do i make an ammo system the unity example fps game has inf ammo and inf reloads but i want to have limited ammo and something you touch to pickup ammo
i already managed to swap the weapon and add casing but negative ammo and permanently running out of ammo is not ideal
did you try googling? there are a lot of tutorials that cover this
for example: https://www.youtube.com/watch?v=cjNMQkODh1M
Setting up an Ammo system is just creating a few integer variables and doing a check or 2. Reloading might seem a little more complicated, but can be done in just a few lines of code.
In this 2d Unity Tutorial learn how to setup a really easy ammo and reloading system you can adapt to your game. It works really well.
I build this off of my 5 M...
oh
if you come across problems while following a tutorial, feel free to ask about the problem though
@cosmic quail should i update?
i want to make a 2d mobile game
and rn i have unity 2022.3.20f1
of course, why not?
unity says its the recommended version so sure. its very recent but it shouldnt have any issues
it's lts,
so its the latest most refined version
i know but if an lts is very new then it may have overlooked issues. it had at least one iirc but it has been fixed by now
yeah, but if you are starting a new game, you should begin with the Latest!
true
So far Unity has been testing this LTS for quite some time. Unless they've been lying to us all, this version should be pretty safe, it is described at least as safe as U5 LTS (maybe even more)
The differences you'll have will mostly be about pricing
yeah i know, also it has the benefit of being able to remove the splash screen for free @dapper arch that's a good feature
what
you can remove the splash screen for free so definitely go with unity 6
its installing anyways
why is it so slow i only have youtube playing
but installing stuff on steam does 50-70mb/s
It's either their server failing to provide higher data transfer bandwidth, your bandwidth being slower than usual, or other factors that make it so that the download is slower
@cosmic quail
the tutorial said to create a new C# script but it dosen't let me add it
i had to use monobehavior
strange
when you want to add a new component from script to the gameobject that script has to be child/derived from MonoBehaviour (it's unity code engine). so make sure your script have that near class name.
well i found a problem
this is what its complaining about
Are you using unity namespace? We may need to see your code in case you're missing stuff
it was the lower cased input

yeah that should have had a red line under it to show you its wrong, you need to configure your ide or you will have a lot of problems like this. here's how to do it: !ide
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
im new to scripting so i dont know much about c# but how do i make it so when a gameobject lets name it for example go1 when go1 is deactivated this code runs
this.schoolMusic.Stop();
is the script on "go1" when it is disabled
sounds like you have a script on go so add an OnDisable method for that code
no
its on a gamecontroller gameobject thats always enabled
but i did refrences
you would just check if "go1" is enabled or not then run that code
https://docs.unity3d.com/ScriptReference/Behaviour-enabled.html
thanks
using System.IO;
using UnityEngine;
using Dummiesman;
using UnityEngine.InputSystem;
public class PressAToInsert : MonoBehaviour
{
private GameObject loadedObjectPrefab;
public string modelPath = @"C:/Users/nathan/Downloads/mesh.obj";
public Vector3 massiveScale = new Vector3(100f, 100f, 100f);
private Vector3 spawnPosition = new Vector3(64.21851f, 231.9479f, 58.24418f);
void Update()
{
// Check if A button is pressed on Oculus controller or A key on keyboard
if (OVRInput.GetDown(OVRInput.Button.One) || Keyboard.current.aKey.wasPressedThisFrame)
{
SpawnObject();
}
}
private void SpawnObject()
{
if (File.Exists(modelPath))
{
FileStream fileStream = new FileStream(modelPath, FileMode.Open);
loadedObjectPrefab = new OBJLoader().Load(fileStream);
fileStream.Close();
GameObject instance = Instantiate(loadedObjectPrefab, spawnPosition, Quaternion.identity);
instance.transform.localScale = massiveScale;
}
else
{
Debug.LogError($"Model file not found at: {modelPath}");
}
}
}
i have this script for oculus and i need help cuz my scripts just crashing
what do you mean by "crashing"?
when i build and run using android on my headset
it will say that it is not responding
after pressing the given button?
no
or just right when you run it
when i run it
The thing you're spawning wouldn't happen to also have this script on it, would it?
seems unlikely to be related to this script then unless the button is always pressed on your OVR: OVRInput.GetDown(OVRInput.Button.One)
nope
But basically you are kind of breaking one of the cardinal rules of interactive programming - you're doing I/O on the main thread
how might i be able to fix that
There's also the problem that you're not properly handling your file handle
You should use a using statement to make sure it gets closed properly
and hwo big is this file
it may just be taking a very long time to read/load it
its 8878 kb
using (FileStream fileStream = new FileStream(modelPath, FileMode.Open)) {
loadedObjectPrefab = new OBJLoader().Load(fileStream);
}``` this is the preferred way to handle filestreams
that's pretty large
certainly bigger than you should try to read on the main thread
It depends how this OBJLoader() library works
im using
but it doesnt even have a rigidbody component??
i mean the object selected
idk why this error keeps on popping up
Does its parent have a rigidbody
wdym the parent?
I mean the parent
im sorry idk what a parent is
the parent is the utmost object in the child's hierarchy
or the parent is an object that contains other objects under it (known as children) in the hierarchy
hey everyone, when i delete an object at start, how do i make it sort the array it was in?
If the size of the collection changes, don't use an array, use a List
And then remove the object from the list when it's destroyed
I was wondering if someone could help me out with an issue I'm having related to Tilemaps. I'm making a 2D game, using a tilemap to create a large map. I have a grid, and two tilemaps under it. One is a background tilemap where I place all my background tiles, and that works fine. The background tiles are solid colored tiles and they come from a sprite sheet that I sliced up. It's a PNG. The other tilemap is for my outline tiles. I'm using a transparent sprite with a square dotted line and place one of these for each tile that exists on the grid. The issue I have is that when I programatically place the outline tiles, they get stretched and look pretty bad, filling the tile up. The interesting thing is if I fill the transparent background with a solid color, the issue goes away and the dotted outline is not stretched. This is not ideal, as I'd like a transparent outline. I'll show an image of both the transparent and solid background examples as shown during runtime of the game:
Am I in the right channel for this question?
Here's the code:
foreach (TileMapData tileData in tileMapDatas)
{
// Generate Vector3Int from x, y
Vector3Int pos = new Vector3Int(tileData.x, tileData.y, 0);
// Key is the position of the tile, Value is the tile data
bgTilemap.SetTile(pos, (Tile)GetTileByGuid(tileData.guid));
// Set outline tile
outlineTilemap.SetTile(pos, outlineTile);
}
I'm using SetTile the same way I'm setting the tile for the background tiles (which are currently working)
hey, I am making a little platformer using Unity2D. I have a smoke animation that plays under my characters feet when I jump (pressing the spacebar). And it Sorta works, The smoke animation plays once when I press the space bar. How do I make it so the animation only play when I hit the spacebar over and over when the character jumps?
Here is a video of What is happening.
Here is my Script for the Smoke appearing and disappearing
and here is my layout
you should probably not be starting a new coroutine every frame
Coroutining is like creating a new thread in the script
So you are making a new thread on your CPU every time
you'd think but no
@rich adder alright so i rearranged my code a little bit, and now it works better. When I jump, the Sprite Renderer appears for a scond then disappears. I jump Again and the Sprite Renderer is enabled but then stays enabled.
oh huh can you not embed mp4
its a spritesheet
FYI, for my issue above this one and for anyone that was curious, I fixed the problem. I believe it had to do with using the right material for tilemap. I switched everything over to use the Sprites-Default Material.
look what it says for Start() comment above
if you want to make it turn off after you jump, then put the StartCoroutine inside the jump.
You probably want to store it in a Coroutine variable so you can figure out what to do if you press space again while its already running a wait, for example you can stop previous and reset it
any tips on flying enemy dashing at player?
What are you using for pathfinding for the enemies so far?
do you already have a flying enemy and are trying to figure out how to make a dash attack, or don't know where to start on creating a flying enemy?
I dont hvae nothing set up for the pathfinding
The only think i have for an enemy is a patrol enemy with to points that it goes back and forth too
Yes have flying enemy just trying to figure out how to get it to dash attack
If your trying to figure out how to differentiate patrolling logic from dashing logic, the simplest thing would be make a small state machine:
public class FlyingEnemy : MonoBehaviour
{
public enum EnemyState
{
Patrolling,
Dishing
}
EnemyState curState = EnemyState.Patrolling;
void Update()
{
switch (curState)
{
EnemyState.Patrolling:
PatrollingUpdate();
break;
EnemyState.Dashing:
DashingUpdate();
break;
}
}
void PatrollingUpdate() { ... }
void DashingUpdate() { ... }
}
If its just how make the dashing behavior itself, you can use a combination of Transform.LookAt() https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.LookAt.html
and Vector3/2 .MoveTowards() https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.MoveTowards.html
Awesome thats for the info! i believe this will help me!
Trying to call my bossScore int from one script and use it in the other, to make the maxhealth scale with with bossScore, but when I try something I keep getting error codes like cannot make void into int, how should I go about this?
what exactly is the error and where are you getting it?
Well, I am recieveing a few, just trying to call the variable from one script to the other, with this code I am recieving none, but I still want to call the boss score int variable
You need to show us exactly what error you're getting and where and with what code.
but currently it seems like you're probably coding without a configured IDE
So you should probably start by configuring it.
we can't help you solve a problem when you don't show us the problem
Okay how can I got about that?
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
Yes, I understand, right now I am not getting error codes, but I just dont know how to call my boss score int form one script to the other and use it as a variable, right now I can only use the void functions
you just access it like you would any other member
right now I can only use the void functions
What do you mean by this? What's stopping you from accessing the int? What happens when you try?
When I try to set bossScore = BossHealth I get this error
Because that line makes no sense
of course, because your BossScore is the entire class, not the score itself
BossScore.instance.currentBossScore
Is this what you mean^ ? @radiant glen
I'm very confused about what you're even trying to do with that line of code
Maybe... I want to set the boss score which is in one script, to the bosshealth which is in a diffrent script
What is BossHealth, anyway?
when you do a = b; the thing on the LEFT of the = sign is being changed. the thing on the RIGHT of the = sign is being read only.
The BossHealth is the maxHealth the boss can have
ok, consider where the boss score is stored though
whya re you trying to change it then? This code doesn't make sense.
it's in the field, int currentBossScore, not the type, class BossScore
the word before the name tells you what it is
In BossScore.cs script
no
no, not the physical code
er, i guess no physical, but not the text of the code
the structure where it's stored
it's inside BossScore, it's not BossScore itself
I still think you're not even understanding how = works and probably have the order backwards.
it's like you're trying to change a line in a document, by replacing the entire document
the document has more than just that line, so that doesn't make sense
in addition to not understanding references and variables.
I am lost sorry, I have a BossScore int in my BossScore script which is increased or decreased based on actions inside of the game, in a diffrent script, I want to call the BossScore int so I can use that number to set it equal to the health of the boss therefor the Boss's health is diffrent depending on what you are doing in the game, I hope this explains it
you don't have a BossScore int
you have a __current__BossScore int, inside the BossScore class
I want to call the BossScore int so I can use that number to set it equal to the health of the boss therefor the Boss's health is diffrent depending on what you are doing in the game, I hope this explains it
You have this completely backwards. Why are you saying:
so I can use that number to set it equal to the health of the boss
It sounds like you are trying to chang ethe boss health
if you want to change boss health you need to do:
BossHealth = something
Again = sign changes the thing on the LEFT side of the =
not the thing on the right
Yes! I want the BossHealth to = currentBossScore
So do it
I think I see now thank you guys!
BossHealth = BossScore.instance.currentBossScore;
That worked, I truly appreciate the help from you guys!
Get your IDE configured
we're not even supposed to help you unless it is
Okay, I have followed all of those steps and it jus is not working...
I think I am going to go back through and check though
You missed one or more steps.
Okay!
I got it working. I made it a particle instead of just a sprite
what is the problem with rotation? when I lock it from rigidbody the chain doesnt work.
each of them are rotating individually. The start of the second segment should be attached to the end of the first segment, and so on and so forth
I'm not sure how you set up your chain here
how can i reference a tilemap in my script without using public Tilemap tilemap and dragging it in from the hierarchy?
you can see in the video
I used hingejoints
you can GetComponent<TileMap>()
but dont do it at runtime in update
was just planning to do it on void awake or start
does it matter which i use? kinda beenn using them interchangibly
Awake happens immediately, before start. Let's say you instantiate something. Awake is called immediately when the object is instantiated, while Start is called at the beginning of the next frame.
can anyone help me with this problem
this is the code and my error is
i know that the (20,48) is talking about the line (20) and character (48) and it says i should have a ; at character 48
the ; is on the 47th character but even if i put it on the 48th it still gives me an error
and if i remove it entirely it gives me a whole new error
You need to configure your !ide before doing anything else
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
how do i do that
Have you read the message at all?
just read them mb
i fixed the issue i just did the ide and used the quick solves
next time look at your own code. If you compare line 20 with line 22 of your screenshot you will see the very obvious differences in what should be, essentially, the same code
I'm glad they asked, as now they have a functioning IDE and can learn that easily
indeed, which is why I did not reply until they had fixed that
I know this isnt an excuse but i just started to learn code yesterday, and i thought id learn it by watching videos that write the code and explain it at the same time. So i just followed the video accordingly which is why i didnt know any better, idk why his was working and mine wasnt though maybe because of the version difference? just a guess
His code wasn't the same as what you wrote
you need to add the text mesh pro namespace to the script . . .
where do i add that
at the top of the script. you should have a red squiggly error underneath TextMeshProUGUI. if not, make sure your !ide is configured . . .
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
the IDE will pop-up a light icon that suggests how to fix it . . .
IDE is not being configured but i don't know what the problem is
and the suggestion is not helping
Try to unparent them, usually that weird scaling issue happens when the parent has a different size from the children, im pretty sure thats whats happening here
screenshot your complete IDE window
its already installed but it does nothing
There's more than 1 step to configuring VS Code
also unity by default opens my Visual studio app
The extension shows an error. Click the red block at the bottom
so why is the script not working
@dire grove post your code here using the appropiate thing from !code and provide the animator again
📃 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.
Thx
wait sorry
Read the error ....
i don't think this is important for my project error
!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.
thank you sherlock i still don't know what the problem is
It says the .NET SDK is not installed.
Why is your game in onedrive, move it out of there
Use git if you want a backup
Onedrive is prone to breaking unity projects
my entire desktop is and i don't know why microsoft did this i uninstalled onedrive and everything still has that
Your user is called OneDrive lol
Wait what
i am Asus
i don't know what microsoft was smoking but i am Asus
@tawdry quest what is problem
its complaining about TextMeshProUGUI but its written right
Again, your IDE is unconfigured, you have an error that says that the .NET SDK is not installed. This is a basic part of the configuration instructions you were linked
@dire grove erm you do animator. but never create a reference to said animator
Thats the problem
man i was following a tutorial
Bad tutorial ig
so how do i tell it to install .NET SDK
also
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
i did exactly as instructed
Or you skipped a step in the tutorial by accident
i linked you the instructions for configuring your IDE. just because you installed a Unity extension from VSCode does not mean your IDE is configured with unity. follow the link as you were told multiple times . . .
his player was working just fine 😭
You need to have a reference to the animator
i checked twice
yes he does, scroll down
i did exact thing as the dude
@dapper arch if lost https://dotnet.microsoft.com/en-us/download
What in the ....
IDE configuration never asked me to download .NET only 2 extentions for VS code
@dire grove did the tutorial guy put that Animator animator; down there too and not at the start ?
Or was that you
i did exact stuff as him
@north kiln do you know why its complaining about TextMeshProUGUI
They've changed the instructions, it used to. Maybe they only list it in the Requirements section of the C# Dev Kit, or perhaps you haven't yet restarted/logged in and out after installing it.
should i share video link?
Once you install the .NET SDK and restart it will be plain as day, so just do that?
Yeah the guy sounds incompetent if he puts declarations of variables mid code
screenshot your animator transition conditions
is there something wrong with TextMesh?
No.
Maybe import the TextMeshPro asset
tbh Unless you have a good reason to use VS Code just scrap it and install VS Community

what
What what
should i share all the transition conditions
There's nothing wrong with it, they just need to install the .NET SDK and relog so it's on their PATH
its showing stuff
The red error you showed me clearly stated that youre missing Text Mesh Pro, so go install it
yes, the return conditions
Great, now you can easily fix the problem
The type or namespace name 'Foo' could not be found (are you missing a using directive or an assembly reference?)
but i still don't know what the problem is

exactly what we've been trying to get you to do since the beginning . . .
you are missing a using statment so add it
the answer is literally highlighted in blue (in your picture) . . .
Without that you wont come far anyways
so all i was missing was this?
Yes
youtube tutorials made me build a whole game with 0 understanding of C#
ok, so there is your problem, in your properties you need to set both bools not just one
tbh you would be better using something other than bools for this
is moving = true? for both
Yeah but thats not how you learn and actually make games you want to make
as i mentioned from the first post; you need to add the text mesh pro namespace in order to use any of its types. just like you need the using UnityEngine; namespace to use any of its types . . .
how so
it will make your transition conditions easier to understand. or you can use an Any State state to simplify the transitions
Please keep the inappropriate statements off the server thanks
{
base.OnCollided(collidedObject);
if (isInteracting)
{
OnInteract();
isInteracting = false;
}
}
protected void OnEnable()
{
interact.action.performed += PerformInteract;
}
protected void OnDisable()
{
interact.action.performed -= PerformInteract;
}
protected void PerformInteract(InputAction.CallbackContext obj)
{
isInteracting = true;
}
protected virtual void OnInteract()
{
Debug.Log("OnInteract() is executed.");
}
}```
jello friend.
these lines of code made my button Interact pressed twice (or maybe more) when i press it only once. why?
I need some advice, I am a complete noobie at coding C# and I want to gain more knowledge of c#. What should I do I'm kinda lost. I have escaped from tutorial hell as it wasn't helping me at all and I wanted to use my own brain to figure things out. How can I figure things out when I don't know how to do stuff? What would you do in my situation?
did you do coding bootcamp?
No I'm a noobie to coding
whenever i add curly braces, it keeps giving an ''problem'' even though everything works fine in the tutorial
if statement doesn't use ;
oh
Your IDE is giving you some help there with the squiggles
i didnt see the squiggles lol
technically it could, it just wouldn't do anything
to clarify; statements like if, else, while, for, etc take a single statement as a body, which is why if (c) DoThing(); or while (c) DoThing(); work.
there's 2 "special" statements that don't really say anything, the empty statement ; and the block statement {}
the empty statement just does nothing. it's sometimes used to indicate, "i didn't forget, i just don't care" or to really just do nothing
the block statement can hold other substatements, which execute in order
if (cond) { stmt* } isn't the structure, it's if (cond) stmt where {} is a single statement that holds other statements
(c-family languages inherit this behavior)
@inland dirge First lesson is to follow community conduct. Don't cross-post.
do you guys tend to look more to microsoft's documentation of c# or unity's more when developing client side things?
Depends on whether I want to know something about C# or Unity. There isn't much overlap between these docs
What is that ?
#📖┃code-of-conduct. Don't post the same content across channels.
Hi, I am new here and exploring this field. I wanted to know that currently I am using C++ in my college for coding problems. To switch into game development, do I completely switch to C#, I don't know if I should do them both or just one.
different languages have different usecases
the more you know, the more you'll be able to do
don't just drop one because you're starting another. you can put it on hold, but you won't forget those skills anytime soon
experience in any programming language translates to a better time in any other, since you'll already know how to program, you'll just need to learn the features, syntax, and interfaces
i figured, i've just found myself going to unity's documentation more than anything recently
is there any specific situations that you would want to go to microsoft instead?
c# docs for csharp language (ie, enums, properties, delegates) and interfaces (primarly System, System.Collections, System.Collections.Generic, in this case)
unity docs for unity features and interfaces
by "interface" here i mean API, not the type interface
Yea you don't have a need to visit C# docs if there isn't anything about C# (language, runtime*) itself that you need or want to find out. There is a lot to Unity, so spending a lot of time there isn't surprising.
ty! 
Is there a YouTube channel for Unity C#?
From basics
Imphenzia and !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
do not get solely dependant on youtube though
try to retain all of the information you receive by practicing
i always recommend books for stuff
yes books are good
bc they normally focus on teaching you the concept and challenging you to find out where to find the info you need to solve a problem you have
i'm an airplane mechanic in the military, so there is a lot of overlap between that and programming
all you need to know is the concept of what you're doing and where to find the information that takes you through it
but this only applies if you can get one or already have one
Any good books?
you're an A&P?
sweet man
i would recommend doing unity learn and a math book side by side
not a&p, just an avionics technician in the navy haha
but i can't talk about it too much since it isn't on topic here, just where the overlap meets like i said
student pilot here 😁 but yeah its off topic
stackoverflow best book
just don't stop reading at the questions
a surprising number of people do
"i got this from stack overflow [link]" and it's from the question...
also books are a real world copy of information that you can use anytime without you needing the internet, I have a C# book and it explains everything you need to know as a beginner, But you need to retain that information or it will be useless
I do not know if unity has their own book, most likely not
"offline documentation"
that's about it lol
than you very much
best seller for programming in 2028
in my game the player can talk to an npc by pressing "E" in their vicinity. if the player is moving at the same time they press "E", they start talking to the NPC whilst moving in one direction forever regardless of input until the dialogue is finished and the dialogue box closes. how can i fix this?
You return early when dialogue is opened in your update loop so your velocity is now stuck to the last read value
Set the velocity to zero when dialogue starts
i think thats what causing the issue but another issue arises if i do that because if i the place if statement after ProcessInputs() then the first issue gets fixed but the player is able to move around during diaogue which i dont want
one post up for the fix ;)
If you were just using forces, that would actually resolve itself
setting the velocity to 0 unfortunately didn't work, i think i'll probably just follow your advice and use forces instead. thanks for the help!
If it didn't work you did it wrong but using forces is probably better overall
sorry, where did you want me to set the rb velocity to 0? i set it to 0 after the interactable check but i think i misinterpreted you
When the dialogue starts
if (Input.GetKeyDown(KeyCode.E) && dialogueUI.IsOpen == false)
{
// here
interactable?.Interact(this);
}
the problem still persists sadly
You also have to prevent it from setting the velocity when dialogue is happening
sorry i don't understand could you explain further?
Do you know where the code sets the player's velocity?
nowhere else besides PlayerMovement
Show your current code
Yes, where in PlayerMovement? In which method?
Hello
I want to use in a script the function collider2D.excludeLayers but I don't see how I say if I want to exclude or not a layer ? Can someone explain me, there is no example in the documentation
it isn't a function
that's a public field, you can set it in the editor
if you want to modify it in code, you could modify its value or create a new LayerMask to replace it
How can I change its value ?
like any other value
it's a bitmask though, so be aware of that
A bitmask is a representation of many states as a single value.
i'd recommend you just use the inspector if you can though
if you use visual scripting in unity can you use classes and stuff in other visual scriptings and can you use it in c#
How can I prevent wall sticking w/o using a 0 friction material?
so like if you make a class or variable in visual can you use it in C#
You can setup corner cases, when in contact with the wall (from specific angle) zero out your own friction.
why would you though. friction, or lack thereof, is the built-in way to manage that
ok
Disallow moving in the air into a wall with a Raycast e.g.
If you think about it objects in real life cannot push themselves into a wall in midair and that's the root of the problem
is it allowed to turn on pings when you're replying late to someone who helping you earlier?
okay
hi, sorry for my late reply. it's velocity is being set in the FixedUpdate() function
rb.velocity = new Vector2(moveDir.x * moveSpeed, moveDir.y * moveSpeed);
(that was not a silent ping, but hey, more power to ya.)
(why not moveDir * moveSpeed btw)
You need to zero out moveDir if it still has value during dialogue, or put it behind condition.
omg sorry 😭 , i don't really know hwo to silent ping in discord, i thought that you add to click the "@ on" thing
that disables the ping entirely
you can prefix a message with @silent and have an actual mention (including a reply) and it'll have the mention bubble thing without triggering a notification, like this one @sterile radish
Right, and you already know how to stop methods from continuing when the dialogue is happening. You already do it at the start of Update
yes, what are you implying by this?
you can check to see if it's appropriate to add velocity before doing so
So when I said that you can fix the issue you're having by preventing the code from setting the velocity when the dialogue is happening, you now know how to do it
oh right, this fixed my problem! thank you so much for your help! ^ ^
Guys, im a bit confused with what I did wrong. I tried to check with chat gpt but it still isnt working. I don't think i connected my restart and quit button correctly to my script. Because in my "GameManager" script i tried referencing them and then tried connecting them with the on click on the inspector tab. But the script still isn't working how I intended it to
maybe share the !code for the Restart method ?
📃 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.
'''cs
// void Start()
{
UpdateScore(0);
UpdateTime(timeRemaining);
gameOverText.gameObject.SetActive(false);
restartButton.gameObject.SetActive(false);
quitButton.gameObject.SetActive(false);
'''
//to hide during the gameplay
'''cs
// public void GameOver()
{
Debug.Log("GameOver called");
gameOverText.gameObject.SetActive(true);
restartButton.gameObject.SetActive(true);
quitButton.gameObject.SetActive(true);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
'''
//to reappear when the game is over. My game over text appears but not my buttons
if you use visual scripting in unity can you use classes and stuff in other visual scriptings and can you use it in c#
so like if you make a class or variable in visual can you use it in C# or other visual scripting scripts
oh ok thanks i see that a lot of people dont get answered there so i hope someone answers XD
well your other option is to try it yourself and see
yea true XD
So i have a bat and i set it as kinematic so if can stay in the sky flying, but when i add my knock back to it when player hits it it just goes flying in the sky... but it i change this to dynamic and have gravity on 1 it wont do that and knockback works... how would i fix this for my bats knock back to work and stay flying in the sky?
maybe add linear drag instead of using gravity?
So keep dynimatic and add linear drag? trying now
or have it ease back to a specified height
If you want physical realism, bats fly using lift force from their wings.
So you'd add forces up when flying to counteract gravity
How do I make objects not collide with the camera?
why would they? unlessur camera has a collider on it?
no it hasn't
howdy, this code seemed to work last time i opened the project, but now the bool for being looked at isnt staying true when being looked at, and only flickers on intermittently. I dont think ive changed anything but apparently i did, do yall have any tips?
thats what im saying..unless ur camera has a collider on it it shouldnt be colliding w/ anything
Not enough context here. We have no idea what's calling these functions or what's reading the bool
Why use send message btw
(just saw the third image)
Your logic around line 33 is wrong
Im just using an if statement to detect if its being clicked while being looked at (getmousebutton && is being looked at)
I don’t really understand that script, I made it with the help of chat gpt
You need to handle the following cases:
- your Raycast is hitting the same target as last frame
- your Raycast is hitting a different valid target from last frame
- your Raycast is hitting something that isn't tagged as a target.
Well then of course you're going to have problems
Don't use code you don't understand
share your code using a patebin website or something so i aint gotta squint
https://pastebin.com/JGFhDVsj think this is how its shared
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.
thanks
trying to understand it, but still need to make progress with the prefabs in the mean time to keep up with stuff
so is it an issue of activating too many targets at the same time?
i figured the raycast stops when it hits one colider, and so couldnt hit multiple at the same time, is that not the case?
No, where'd you get that from
Yes, indeed that's how raycasts work. But you are running this code every single frame. There's a new Raycast each frame
i still cant get it to behave right...
i think Praetor is on to something.. i think you dont have enough logic to do what u want to do..
you probably need logic to check if the target was the same as last time..
if it is hitting a different new valid target we should tell the old target that its looked away from.. and the new one that we're now lookin at.. or if ur raycast hits something that isn't valid we could check if there was a valid target last time.. as lookaway from it.. etc
ok. so could i make a seperate gameobject variable like OldTarget to test against, and a bool to say whether the target is valid or not, and fix the logic?
Ray ray = new Ray(cam.transform.position, cam.transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, maxDistance, targetLayer))
{
// new target was found
GameObject newTarget = hit.collider.gameObject;
// if the new target is different from the current target,
if (newTarget != currentTarget)
{
if (currentTarget != null)
{
// notify the old target (if any) to look away
currentTarget.GetComponent<TargetBehavior>()?.OnLookAway();
}
// notify new target its being looked at
currentTarget = newTarget;
currentTarget.GetComponent<TargetBehavior>()?.OnLookedAt();
}
}
else // no target is being looked at
{
if (currentTarget != null)
{
currentTarget.GetComponent<TargetBehavior>()?.OnLookAway(); // notify old target to look away
currentTarget = null;
}
}
}``` heres all those conditions
should be able to do it with just 1 variable
if we're lookin at a new target (check the old target first.. if its different than look away from the old one look at the new one)
if theres no current target then we can just look at the new one
if its the same target we can look at it again.. or do nothing.. thats up to you and ur game
i do the same w/ an interact raycast.. (we just cache the result).. then use that to do any comparisons on the next frame or the next time we look at something
ok
why are you using SendMessage? just curious
thats how chat gpt said to do it
ahh, ok.. makes sense
So blendshapes and BakeMesh() work, but extremely expensive, before I go another route to use or not use skinnedmeshrenderer, is there a cheaper method to find the highest vertex of a skinnmesh?
all i really want is a bool saying whether an object is being looked at or not, so i didnt look as far into it as it seems i should have now
if you want something to tell you what its looking at, use a Raycast
is that not what im doing here?
i was just curious.. i just used regular functions.. and after i grab the component i just call the method
forgive me i did not scroll up far enough
heres how you could check a bool.. just put that logic in ur methods for lookin and looking away
then each TargetBehaviour would change depending on ur raycast logic
is that rider? or is that the intellicode from VS doing that
codieum/ vscode
would this be ran on the camera or on the gameobject
its really helpful imo.. i can write out the variables at the top of the script.. and a few function names.. and it can pretty much guess the simple stuff
the targetbehaviours are on all the objects we can look at
the raycast script i used could be on any gameobject. b/c it uses the MainCamera tag to find and use the camera as the rays starting point
So im able to get exactly what i need, but using BakeMesh() is expensive. Is there any cheaper method? Heres a short vid on what it is supposed to look like.
here you can see that boolean i just made
ok, i currently have the look at script on the camera, is having it on the game object more effective?
when i select the red object the boolean flicks on and off depending on when i look at it
doesnt really matter.. (if ur using the main camera tag camera.Main it can be on any gameobject...
some people put their raycast logic on the camera.. and use transform.position instead
its up to you
ok
lmao, everything i try to do always ends up a lot more complicated than i expect
// Create a ray from the camera's position and forward direction
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;``` this one would be on the camera itself (using transform.forward and transform.position)
// Get the main camera
Camera mainCamera = Camera.main;
// Create a ray from the camera's position and forward direction
Ray ray = new Ray(mainCamera.transform.position, mainCamera.transform.forward);
RaycastHit hit;
``` this one could go on any object.. b/c we're grabbing the position and direction from the camera no matter where it is
thats game-dev in general.. and it only gets more intense 😄
the last 20% of building a game.. takes 80% of the time
80/20 rule
There are going to be a ton of these game objects (they’re buttons for a control room), would there be a significant difference in computation? We’re going to need a lot of computer power to run calculations in the background
from what i remember SendMessage can be performance heavy if ur running it all the time.. by Directly referencing a component you avoid some of that overhead.. https://discussions.unity.com/t/is-sendmessage-really-that-bad/404624/2
Ok
Find what common Unity optomizations truly make a difference. In this video I go over a bunch of interesting optimization tips as well and give you my recommendations on each.
Keep your code running fast with as little garbage allocation as possible by learning from these important concepts.
Benchmarks (let me know if you get weird results!):...
Thank you
hers a little video where guy goes thru and does optimzation tests
i think he even does SendMessage in this example
Ok
Ok
Chatgpt just doesnt know 😈
Humans > ai
for now 😄
heres a hint.. if you must use AI..
make sure to tell it how you want it done..
when you learn things like send message being slow for example..
point that out to it.. and have it refactor/ come up with better solutions
Ok
or use google which is better than AI
i've swapped.. when I must use AI i use Gemini now
I just don't use AI as the unreliable answers are error prone and are slow, it will probably just steal from stackoverflow anyway 🤷♂️
ohh 💯 it will lol
procedural mesh creation instead?
could I get that to work with multiple types of branches and leaves?
why not use VFX graph for that?
seems like something it'd be perfect for
https://www.youtube.com/watch?v=IZH41PqeTY0&t=90s&ab_channel=DVSDevs(DanVioletSagmiller) or something like this
I've been working on a variety of ways to "grow a plant" on #unity3d, and in this example, I'm experimenting with deforming a mesh to reshape a quad and grow the stem and leaves of a plant.
If you like the content, please consider supporting us on Patreon and joining our Discord to discuss Unity, game building, and code
https://patreon.com/Dan...
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.InputSystem;
public class CharacterController2D : MonoBehaviour
{
private Rigidbody2D rigidbody2D;
private Vector2 movementDirection;
public Animator animator;
public float moveSpeed;
private void Awake() {
rigidbody2D = gameObject.GetComponent<Rigidbody2D>();
}
private void Update() {
Vector3 moveDirection = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
transform.position += moveDirection * moveSpeed * Time.deltaTime;
moveDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if(Input.GetKeyDown(KeyCode.Space) && rigidbody2D.linearVelocityY == 0)
{
rigidbody2D.AddForce(new Vector2(0, 20), ForceMode2D.Impulse);
}
}
private void FixedUpdate() {
animator.SetFloat("Horizontal", movementDirection.x);
animator.SetFloat("Vertical", movementDirection.y);
}
}```why does it keep playing the idle animation, even when I'm moving?
You are not writing new values to movementDirection anywhere, so the vector will keep its initial value
so what do i do?
I guess here:
moveDirection = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
You meant to assign to movementDirection instead of moveDirection?
On line 22
no way i did that🤦♂️ sorry
Hes close but not there yet. I dont think he can deal with moving something along the vertex of another blendshape. This stuff is hard DX i havent heard of vfx graph ill look at it
ya, not the easiest mechanic to make
When the runtime yells at me about a null reference of a line, does the output specify what exactly it is that is a null reference?
NullReferenceException: Object reference not set to an instance of an object
UnityEngine.AI.NavMesh.CalculatePath (UnityEngine.Vector3 sourcePosition, UnityEngine.Vector3 targetPosition, System.Int32 areaMask, UnityEngine.AI.NavMeshPath path) (at <77c95d4fdf1c463496f3c7ba3c00fe51>:0)
NavMesh.CalculatePath(
state.Me.transform.position,
state.Enemy.transform.position,
NavMesh.AllAreas,
state.NMPath
);
I can't tell if it's state, Me, Enemy, either of the transforms, etc., I think it's not NavMesh because that's a static class
debug each value before you use or comment em out one at a time
should be able to figure out which one is null
Is that a no
it wont tell you specifically which one is missing.. just the line it occurs on..
to pinpoint the exact cause you should
- debug the values
- use error checking / catch the error when it happens
- use debugger and breakpoints
I know that, and that wasn't my question - I was just hoping that the error message would tell me where the null reference is outright
if (state != null && state.Me != null && state.Enemy != null)
{
NavMesh.CalculatePath(
state.Me.transform.position,
state.Enemy.transform.position,
NavMesh.AllAreas,
state.NMPath
);
}
else
{
Debug.LogError("One or more variables are null!");
}```
no
i answered as well as gave methods to help you figure it out
you could probably turn on Debug mode in the inspector to check which variables are assigned or not.. that'd be the quickest way imo
for example PickedUpObject is a private variable.. but debug mode allows me to quickly glance and see if its assigned the way it should be during runtime
without doing anything extra
Obviously I know this doesn't work, but is there a generic way to copy the fields over without reflection?
i just want to make a vr game
Anyone know a fix for Visual Studio (not vscode) constantly losing Unity based intellisense?
I have a stock setup, installed unity through the hub, selected to install VS, installed the Unity VS extension, its connected and works the first time I boot it but then stops.
Heres an example: you can see Unity specific namespaces are not colored
Lot of people reporting that issue lately
in reference to above ?
i need help on fixing this bug.
Yeah, linking seems to become removed when the project becomes updated. I've had it doing it to me too, but I'm been using vs code so I've not the need to debug it ;p
yup
VScode has been slower than VS for me for some reason
so for my game i made a "ai" that will follow the playe. but if you go up a level is elevation it jiggles and something. and it clips into corners
VSCode been solid for me as well. Just updated it.. still linked as should be 🙂
even while bugging me about not being signed in..
I didn't even know you could sign into VScode.
i do need to grab rider while im thinking about it.
no harm in having all 3 editors >8)
uses ur Microsoft Account
for what?
liscensing i guess
Seems to work fine without it lmao
it says "sign in ur microsoft account to use c# dev-kit"
but its been working fine w/o the sign in
it does a miserable job at stopping you if you don't sign in.
yeah
The reason I decided to use VS, is because I though it was more solid than VSCode... i guess not.
Is Rider... the most solid? (God forbib one of them implements the language server correctly... hehe)
people will say VS Studio is a fully fledged IDE while VSCode is just a fancy text editor..
i like VSCode.. b/c with the right extensions it does everything i need it to do..
and I can use it when developing for MicroProcessors etc..
when it comes to being the most solid.. i think it goes
Rider > VS Studio > VS Code
People say it's a nice program, I use VS and VSCode and they both work for what I need them, I have no opinion's on Rider since I have never used it
VSCode imitates a real IDE via extensions
I need... a program that can read and edit ascii, run a language server to syntax highlight and give intellisense, and save ascii.
Thats it...
😁
im joking... yeah ill probs setup vscode now
heres a list of extensions if that what you chose..
ignore the PlatformIO and the C/C++ .. as those are extra for embedded chips (programming microcontrollers and stuff)
the rest are super useful tho (Codeium can be omitted as well, its just a built in AI-tool)
Rider is free now btw
Just dont use their macros :p
I know VSC is more lightweight but right now it has been acting up for me, the base extensions for VSC are Unity Code Snippets, .NET Install Tool, C# and Unity for VScode People say you do not need Code snippets but for me some functions do not show up if I do not have it
you don't need codeium or C/C++ or winter is coming theme, I didn't even know you could install themes
This isn't a specific question, it's moreso to confirm a hunch i'm getting:
I'm not really a programmer, mroe on the 3d modelling\ux part of things
I'm working on what's essentially a Tech Demo, and so far everything seems pretty straightforward programming-wise, i have a rough idea of what subroutines are but never really use them, i can use switch statements and golly gee my stupid ass even learned how to make a subclass the other day, i'm even avoiding the stupid meme stuff like a bunch of if else statements in a row, even having the most basic understanding of programming, i'm getting by so far.
But the thing is, again, i'm working on a tech demo, nothing's really scalable, i doing all the "assets" by hand (what would be repeated\dynamically spawned), right now i'm only working with vectors, the basics of the basics of physics, some UI stuff, raycasting, getting bounds, what i think is fairly low level stuff, so my hunch is:
Am i just working with the overtly simple stuff by chance (and some of you here will know that two weeks ago it wasn't simple for me) or does scripting really gets REAL difficult once your scope is fairly big? like, making ONE thing is real easy but making MULTIPLE things that connect and talk between one another is where the real difficulty's at?
if ur learning i say let it happen organically.. refactor as you go.. when u learn something new/better replace the old stuff..
If it works it works.. don't dwell on optimizations until you need em
if you do not overwhelm yourself and are actively learning you will be fine
that's what i'm doing right now, i know i need to do something, i look up a tangentially-related tutorial, try to take what i need from it and implement, and so far while it hasn't been smooth sailing it's moreso that when i hit the solution it's "oh, it's that simple"
I find myself second-guessing my decisions a lot or asking myself "ok but how to the REAL programmers do it?", i don't know if you lose that eventually and if you do, when
ahh, you'll find urself on the other side of the table soon enough
"oh, this is way more complicated than it seems"
- Are we allowed to change the execution order of OnEnable methods of objects, or is that something we should NOT try to do? I want Obj A to always have its OnEnable called before Obj B.
- This is because OnEnable has an event subscription, and i want to prevent workarounds like introducing a new event
you can do this using Execution Order
That's how it started tbh
First question i asked here (i think) was trying to implement the transform functionality from the editor at runtime, like, have an axis and drag an object around in that axis, i assumed that was pretty simple
(turns out it wasn't)
but hey now i know how to raycast and create planes and project points so that was worth a lot of knoweldge
if you want one scripts OnEnable to run before the others you can assign them in this menu
use google as it is your friend, Do not overwhelm or burn out or you will get unmotivated, and DO NOT make huge projects as a beginner start small, always keep learning as well
but when i did get it working i got to "oh damn that wasn't so hard"
https://medium.com/@report.vector.focus/optimizing-script-execution-order-in-unity-8f040746be2b @spiral narwhal a good article w/ info as well as alternatives
oh man there goes my dream of building my procedually generated roguelike voxel based third person crafting game with destructible environments 😦 /jk
Hmm, am a bit confused. Am trying to do PlayerInfo loadedInfo = JsonConvert.DeserializeObject<PlayerInfo>(File.ReadAllText($"{_playerDataDirectory}{_slash}{PlayerDataFileName}.json")); where PlayerInfo is a scriptableobject. But I guess you can't do this with scriptableobject classes?
with real-time Day/Night cycles and cross-platform multiplayer?
And an optional VR mode as well, how'd you guess???
im doing the same project! 😅
How are you supposed to deserialize scriptableobject datatypes
I guess you have to make a regular class which contains all the data for that scriptableobject...? Blegh, so redundant
How are you supposed to deserialize
Fala galera. To começando agora e nunca tive tanto problema na vida como estou tendo agora, que puder por favor me salva
hablas inglés?
more or less
thats what i was thinking.. the GUID right?
Having problems with the scripts and for some reason with "+="
I'm not sure if it's the code or something else, I started studying it recently
Yes
📃 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.
+= work like
thisValue += thatValue;
thisValue = thisValue + thatValue;```
so i have a texture i need to update very frequently during runtime thing is its a high resolution texture how would one go about doing this, is there not a way to update only part of a texture?
instead of the entire thing
Can I send images here to make it easier to understand?
just share your code the way the bot described
I put a code in one of the links but I don't know how to use it.
share the link
and what is the actual error you are receiving?
Assets\Scripts\Enemy\MeleeEnemy.cs(19,9): error CS0019: Operator '+=' cannot be applied to operands of type 'UnityEvent' and 'method group'
UnityEvent is not a delegate that you can += to, you call the AddListener method on it
Hey, is there a way to fade out button with text without fading in/out button image + text separately?
instead of fading the button or a canvas group.. just fade out the text color's alpha
Thanks!!! I managed to fix the problems❤️
But I need to fade in/out both button image and text, will it not just fade out text alone?
you can put a Canvas Group component on the main gameobject and use that to fade all the elements that are children of it
Thanks!
Do those settings change default behaviour of a button?
"block raycasts"
it shouldnt
ur just changing the alpha..
the elements are still there
Yeah I mean the canvas group adds some properties
it may be..
i was thinking that.
i'd just test it both ways
see if its a viable solution
alright
if not.. you may need to use an array or list of all the components
and fade them all using a forloop or something
but the canvas group should be good enough
yeah it seems to be made for it 😄
👍 good luck
Thanks
Is there a way to check if an animation is finished playing?
let's say i have an animator, when X happens, i want Y animation to play and then do something else in the code
Hi again, I'm having the following problem
UnassignedReferenceException: The variable groundCheck of IsGroundedChecker has not been assigned.
You probably need to assign the groundCheck variable of the IsGroundedChecker script in the inspector.
UnityEngine.Transform.get_position () (at <7b2a272e51214e2f91bbc4fb4f28eff8>:0)
IsGroundedChecker.IsGrounded () (at Assets/Scripts/Player/IsGroundedChecker.cs:11)
PlayerAnim.Update () (at Assets/Scripts/Player/PlayerAnim.cs:25)
Do you know if the problem is in the code?
whats the most optimal system for saving and handling lots and lots of bools deriving from dialogue interactions within my game (for example, the player talks to a road sign and decides to break it, setting a bool true so that next time they play the game the road sign remains broken)?
could you show your !code please?
📃 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.
you need to assign that variable, I'm guessing it is a transform of somekind so you would either assign it via Getcomponent or the inspector, preferably the inspector
That's where the problem is, I don't know which two scripts the problem is in, when I click on the error it takes me to the object
it says what script it is in
and the path to it
at Assets/Scripts/Player/IsGroundedChecker.cs:11
The problem is then in the script, right?
is that variable supposed to be assigned in the inspector?
also we would need to see the code
I'm guessing yes it is some sort of transform, which is public or a serialized private
There are plenty of tutorials on saving systems. Look it up.
It would be assigned to the player to check whether he is on the ground or not
show us your script
I don't know if I understand, would I have to take the script to the character?
no, you would drag and drop a transform from an object into the empty field
which in your case is groundCheck
your script should already be on an object since you are getting an error
I think I understand, you will see if you place yourself in another object
I'm not entirely sure how to respond really, all you would do to fix your error is to do as I said above
This may have a plethora of answers, but:
Is there a "best" way to disable a gameobject after an animation is done playing?
Animation event
For the life of me I cannot find how to make one.
How do I create a string table collection asset.
All of google just talks about how to make one at runtime which I do not want right now
I just needed the localization package 
{
public PlayerInputActions playerControls;
public InputActionReference interact;
private bool isInteracting;
protected override void OnCollided(GameObject collidedObject)
{
base.OnCollided(collidedObject);
if (isInteracting)
{
OnInteract();
isInteracting = false;
}
}
protected void OnEnable()
{
interact.action.performed += PerformInteract;
}
protected void OnDisable()
{
interact.action.performed -= PerformInteract;
}
protected void PerformInteract(InputAction.CallbackContext obj)
{
isInteracting = true;
Debug.Log("isInteracting is " + isInteracting);
}
protected virtual void OnInteract()
{
Debug.Log("OnInteract() is executed.");
}
}```
does anyone know why does isInteracted is being logged twice here? the results also showed that OnInteract is executed twice
(i have a set of 2 doors btw)
is there no way to do this in code? XD i am thinking wayyyyy too hard i think
It SHOULD be, just a lerp or similar, but its not working correctly because I dont have an object instantiated at the end of the branch, just the movePoint, that moves each time it grows. FSR it just stays put, or does some crazy transforms using localPosition, is there a better way to make the two leaf game objects to travel up the branch?
this is what needs to happen, but using BakeMesh() on SkinMeshRenderer is really expensive. is there a simpler way to follow the top vertex of a skinmesh?
sorry this is the only vid i have before i started trying different methods
just moving the leaves using lerp or something works, but doing something like Vector3.Lerp(transform.position, transform.parent.position + new Vector3(0, skinMesh.bounds.size.y, 0), speed * Time.deltaTime); doesnt do anything
transform is the leaf, the parent and skinmesh is the branch
m8, i dont think those cool lines of codes doesnt go to #💻┃code-beginner 😂
hawk tuah XD
yo chat i may have fixed it...
assigning the vector3.Lerp to something really helps
college professors when they ask and answer their own question
I think we went over this before, but why are you using skin renders for this again
theres a problem with just scaling the parent object
child objects reek havock without needing inverse everywhere
blendshapes easily give some length and have perfect mesh distribution. but a regular mesh is either blocky, or super hard to alter a script for different lengths, or types of branches
using the blendweight, i can time each branch to grow, faking the spot it grows with good timing, but the leaves need to follow the top of the mesh
I would probably tackle this using splines, and segment it out as it grew to add branches
quick question guys
i thought of that! there must be a way
theres not alot of documentation
mostly paths, but theres probably a hacky way to had multiple splines.
it just really sucks, even doing BakeMesh() a fraction of the time is still terrible for the game. i spent months getting to that solution lol
Don't ask to ask. Check #854851968446365696 on how to ask questions properly.
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
i know dlich, i been here plenty. Ive been at this problem for months. im trying to find the best performant method to move leaves along a blendmesh. if blendmesh is too expensive then im having an error with my lerp function not going along the local transform. u right tho i was complaining
In THIS case its not following the skinMesh. This method is the Lerp having issues following the world transform and not the local one. the way the code is written I dont know how to make the leaf transform follow the height of the branch, while following the direction of the branch
transform.position = Vector3.Lerp(transform.position, transform.parent.position + new Vector3(0, skinMesh.bounds.size.y, 0), speed * Time.deltaTime);```
Do you have CPU skinning enabled? The bounds may not be updated correctly like this
oo how would i figure that one out?
Don't have Unity open but it's either on the component itself or in project settings
unless there's an instancing bool somewhere
i thought it was GPU instancing or something
i think i have it off, let me double check
well, there's a bit more to instancing
skinning is done via compute shader mostly, but Unity provides CPU skinning for web/mobile builds
for matrix calcs, then instancing is for rendering
yea im in way over my head, and kind of dont know what to research next. I have been dabbling with shaders, but it seems easier to just move the leaf through normal code? i may want to do stuff with it later, and raycast may need to be used on the leaf. I have been researching matrix stuff, but i dont see alot of documentation with how its used in my case
This was not in reply to you.
Like I was saying, splines seem to be the idea if you're trying to some procedural growing. Then sprout some leaves meshes / more splines on the segments would be what I'd do.
my b 😦
Ill dive into that, thanku mao 😮
Hi
i am having some trouble with syntax
{
//key value pair, saving the allskins array as a string to the playfab cloud
{
("Pfp", Encoding.ASCII.GetString(tex.EncodeToPNG()),
("Width", tex.width.ToString()),
("height", tex.height.ToString())
}
}```
how to fix it?
I don't think you can initialize a dictionary like that. Why not initialize it as empty and add the elements normally after that?
API errors
cant do that
or else it wont work
this is the whole result
{
Data = new Dictionary<string, string>()
{
//key value pair, saving the allskins array as a string to the playfab cloud
{ "Pfp", Encoding.ASCII.GetString(tex.EncodeToPNG())}
}
}, OnSetPfpSuccess, OnErrorPfp);```
well you are right
i can do that
I feel like you're confusing C# dictionaries with json objects or some other data structure outside of C#...
yea
fellas, i've got an object that just flies in an arbitrary direction, and i'm trying to check for a collision during its flight but i can't get it to work. i can see that the object does collide with other objects as it passes through them, but the collision method doesn't seem to be detecting anything, as nothing shows up in the console during the collision. the collider is not set as a trigger, and i made sure it has a rigidbody component. not sure what to look into now, so i come here.
void OnCollisionEnter(Collision collision)
{
//EnemyBehavior damageable = collision.gameObject.GetComponent<EnemyBehavior>();
//if (damageable != null)
//damageable.TakeDamage(attackDamage);
GameObject gameObject = collision.gameObject;
if (gameObject != null)
Debug.Log("hit");
}
seems i may have fixed it by setting the object to be a trigger, and using the method that checks for a collision with a trigger. what do they do differently that's giving me the intended result? i thought they would both check for a collision pretty similarly
this resource I've made goes over it all in detail https://unity.huh.how/physics-messages
that was quite handy, thank you. so it seems i was just using the wrong method for what i was intending to do. a little bit more googling on top of that showed me that a Trigger checks moreso for an overlapping of hitboxes, which is what i was trying to do, where the OnCollision methods check for actual act of two physics objects colliding.
do you have any other pages like that? this must have been a common enough topic of confusion for you to have made an article for it
So there is a collection initializer for dictionaries. Good to know.
thanks
are there any particular downsides to creating an empty game object called ScriptManagers, and then shoving every manager type script in it? I kind of just want it to be independent of everything and out of the way, so not attached to a gameobject thats going to be constantly changing
this is what I do too
honestly up to you
some people dont like it
i like it
Only one I can think of is that you cant use DDOL on child objects. At least unity will warn you about it. I usually have like a setup prefab if its like a repeating framework type and that should never be overwritten in any scene except a setting file for example.
This should work fine, what does it say?
You can initialize a dictionary like this, and add new rows the same way.
vas a = new Dictionary<string, string>()
{
{ "Hello", "World" },
{ "Foo", "Bar" },
};
I believe it has to do with some C# trickery and the usage of Add in collections
its just the brackets that are wrong on it
oh sorry i was looking at their first message, not the one you replied to
Ah, no problem 😄
I founded the answer here XD
they dont mention you can use C# variables within visual scripts
well idk i can';t figure it out prob doing normal scripting then 🤣
Sir this is a channel for coding questions, not #763499475641172029 ranting
Why is line 28 causing this Problem? It works fine with card.OnHover
Which of these is line 28? You cropped out the line numbers in your screenshots
apologies, its card.IdleState in "else" within the if condition in the first pic
It compiles, however it is never called due to the errormessage and i cant figure out why
That means card did not have a value (it was null), so that means the GetComponent<InteractableCard>() above failed, which means whatever the raycast hit did not have that Interatable Card script attached.
Ya IDE has a bunch of squiggles which you should probably check out too (not totally related to the issue)
If you're trying to run some code when you stop hovering the card, then you should be storing the currently active card in a field (a variable at the level of the class), so you can keep track of it and execute code on it
Thank you!
I'm actually confused what the IDE is trying to tell you here. Looked like it was warning of unused methods, but it's just highlighting a bunch of random stuff for some reasons
Spellchecker extension I think. Their VS seems to be in German (see code lens indicators above Update), so it might false trigger on these non-German words
Ohh, yeah that's it good eye
I have one for VS Code at work, and the color is similar
<@&502884371011731486> crypto scam
!ban 1305263437672349797 scam
j_biniance_ was banned.
im having trouble setting shader for entire scene
Camera.main.SetReplacementShader(FlexibleCelShader, "Cel Silhouette");
this code doesnt work
all the gameobjects disappear
shader for entire scene? explain
all the gameobjects in the scene which has materials
are you using the Built-In render pipeline ?
yes
and the materials/shaders you want to target have the Cel Silhouette tag in the shader code?
Any objects whose shader does not have a matching tag value for the specified key in the replacement shader will not be rendered.
https://docs.unity3d.com/Manual/SL-ShaderReplacement.html
make sure
wouldn't that tag be in the shader code itself ? like the code on page I sent?
I'm not 100 familiar on this function so just going by what the docs say
I could do this kinda inneficiently with a loop, just wondering if theres an easier way:
Say i have a list of 10 game objects, and i want to remove everything after index 6:
Instead of for(...){ List.Remove(List[i]);
Is there a simpe single command i can use like a:
List.Truncate[6]
or
List.DeleteAllAfter[6];
(Example names but u get me)
RemoveRange
do check the docs next time please
also using a loop yourself is not anymore inefficient; the issue is more so iterating while mutating. you would remove elements 6, 8 then error unless you went through backwards, but it's generally just better to avoid the potential for that mistake and just use the method instead
thx 👍
hello
i did a method and it does not shown on "on click" filed on the inspector of the button
so i have to remove the color parameter
well that's part of it yeah. i only just looked at the second image and saw you assigned the script directly so look at this too
https://unity.huh.how/unity-events/incorrect-assignment
also configure your Vscode ⬇️
hi hi 🫠 im about to ask something really basic, but how can i make a camera move with a button press and stop at the coordinates i want? right now i have this which is fine to controlling it myself, but i dont want to control it myself, i want to press right and it automatically moves right until it stops on the location i want
you would have to define what you mean by "the location i want" to start with
what location do you want
but basically the short answer is something like:
void Update() {
if (Input.GetKeyDown(Whatever)) {
targetPosition = something;
}
// Move towards the current target position
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Time.deltaTime * speed;
}```
it has three positions and i want the camera to move and stop at all three pretty much
Also your whole:
Transform transform; and transform = GetComponent<Transform>(); stuff are completely unecessary/useless
you should delete them
You should put empty GameObjects at those positions so you can read the positions of those empty objects in your script to move towards them
oh so like, if pressed a button move towards object X and stop?
well I showed the code for how to do the moving and the determining of the target position already
all you need to do is fill in the "something" I wrote with code that determines the positions you want
im probably fucking up smthg rly obvious, before i give any input it moves to location 2, and the when it goes from 3 to 2 it locks there automatically
oh right i forgot to delete the useless part
I'm a bit confused with the indentation of the if blocks ({}) that you made
first off you're using GetKey instead of GetKeyDown
Second you have multiple if statements with the same conditions so they will of course both run on the same frame
third why do you have multiple lines with transform.position = MoveTowards
that's not correct and not necessary
It's not even belonging to the if block
Please see my example above
It's just blocks that serves no purpose & are quite hidden on the left part of the screen as they're not indented
i thought if i followed the example for every different location it would work ? sorry
you shouldn't have three different target position variables either.
even though there's three locations?
three stop at variables makes sense
ONE target position variable. It tracks the current target position
oh !
and ONE line that moves towards it at all times
okay so keep just the stop at's remove the target position 2 and 3
the rest of the code should just be deciding what the current target position is
nothing else
i will try 😅 sorry for sounding like an idiot im very new
This is your code flow
if (Right) {
Assign tpos1
}
change transform
if (Right) {
Assign tpos2
}
change transform
if (Left) {
Assign tpos3
}
change transform
if (Left) {
Assign tpos2
}
change transform
Hey there everyone! i'm currently making a upgrade system for my game similar to a typical roguelike level-up system where you get new abilities and or stat buffs
i want the player to be prompted with 3 randomly picked upgrades as buttons for the player to select, some of those upgrades can lock or unlock new upgrades from the pool to have different builds, however i can't find any ressources that could help give me an idea of how to make something like this efficiently!
does anyone have some ressources or tutorials i could check out for a modular system similar to what i want to do?
oooh okay i think i understand what u mean
Yeah brackets are not placed properly imo, and also a I do agree that you may need only 1 target. Another thing is that you are changing the transform quite frequently, which may explain why there are some visual glitches (?), also you don't need to assign transform in start as each class inheriting from MonoBehavior automatically have the variable transform assigned, same goes with gameObject of course, but that's a detail
Last but not least, if you want to assign fields in your inspector, but you actually don't want those fields to be publicly accessible from other classes, you may want to transform
public type fieldname;
into
[SerializableField] private type fieldname;
i will...try my best... when you use change transform in your example is it the same code i have now?
I used pseudocode, the thing I wrote in my 1st message is just a description of the flow of the code you sent
To me the flow is overly complicated and prompts issues for what you want to do
oh were you giving an example that it's what i have right now and its bad- or were you telling me to change it to something more like that 😅
1st one
ahhhh . yeah okay i know that much. doesnt mean i know how to make it better
@carmine star you might want to check out #💻┃code-beginner message
Yes, when you write
if (a)
b;
c;
You are basically writing
if (a) {
b;
}
c;
The if statement with no bracket will, by convention (and as mentioned it is a behavior from the C language) only conditionalize the very next statement. That's why only the statement b is conditionalized by a.
so i need the condition of the location first and then the button press?
no wait i think i got what you meant
i dont want the first thing in brackets cause its part of the condition
in theory this should just work and i wouldnt even need targetposition if i just want a marker of present location right
you've wrapped the second statement in a block, but it's not the statement after the if, so that isn't doing anything
there is no reason to be doing anything with transform.position in this part of the code at all
oh. oops.
and again your if statement syntax is all messed up
you have if (cond) a; { b; } instead of if (cond) { a; b; }
anyways you probably want to just step back for a sec
you're misunderstanding the logic here
so step away from the code for a sec
yeah im probably confusing myself more
get an idea of the problem, then of the solution
and after that, a code implementation
so right now what you want is:
- when a key is pressed, have the camera go to a specific point automatically.
- depending on the key pressed, have the camera target different points.
- regardless of whether a key is pressed, the camera should keep moving if it's not already at the target.
that first one is conditional (on what key is pressed), the last one is not (hence "regardless")
so a system for that, the "solution" could be something like this
is a key pressed?
get the target for that key
is the camera at the target?
if not, goes towards the target
```but really, "going to the target" if we're already on the target would just be not moving, so we could omit the check
is a key pressed?
get the target for that key
camera goes towards the target
||```
let target be some position
if key for targetA is pressed:
set target to targetA
otherwise, if key for targetB is pressed:
set target to targetB
move camera towards target
```||in pseudocode, typically indents are used to indicate the scope of statements, ie what the statement controls. but in c#, braces are used, and indents aren't important to the computer
@carmine star make sure you understand all that before going to code
i can understand the logic of what you are mentioning! i just dont know enough code to know what to write to make such things happen, if that makes sense? im in a post graduate and we only had 10 hours of basics and now we have 11 days to deliever a game with no extra classes 🥲
this does help Understand what I want to do, I'm just confused on what I need to write to make it do it
i thought that as long as i had something like 'if camera at 1 then when key pressed move towards 2'
you could probably just use a list
I do not know if this works, but it would go something like this
[SerializedField] List<Transform> Spots;
int T;
Transform CurrentSpot;
void Start(){
T = 0;
CurrentSpot = Spots[0];
transform.position = Spots[T].position;
}
void Update(){
if(LeftKeyDown && T >= -1 && T <= Spots.count + 1){
T += 1;
CurrentSpot = Spots[T];
}
if(RightKeyDown && T >= -1 && T <= Spots.count + 1){
T -= 1;
CurrentSpot = Spots[T];
}
transform.position = Vector3.MoveTowards(transform.position, CurrentSpot.position);
}
I am most likely getting the list wrong, but I hope it is correct.
i thought that was what i had tried by now but amidst all the confusion i probably messed it up
I would suggest learning the basics if you haven't already #💻┃unity-talk message
you would want to use GetKeyDown as it only calls whatever is in the if statement once while GetKey calls continuously as long as the key is held down
oh that i can at least understand thank you
i will check out the basics again yeah, its impressive how the more i try to fix it the less it does what i want
when i recorded that first attempt at least it moved
definitely a few issues with casing there
also CurrentSpot is redundant to T, and T would be an int there for an index
and it'd need to check that T wouldn't go out of bounds i suppose
yeah forgot it was an int, and yes I should check if it is out of bounds
is there a simple way to render a Texture3D to the scene?
fixed the mistakes
yes I know I am nesting but its not that bad
uhhh that's not how you do it
There's just the case where your CurrentSpot is null (if I'm not mistaken)
Assuming LeftKeyDown & RightKeyDown are checks to perform using Input
||```cs
[SerializeField] List<Transform> positions;
[SerializeField] float maxSpeed;
int currentPos = 0;
void Update() {
if (positions.Count > 0) {
if (LeftKeyDown && currentPos > 0){
currentPos--;
} else if (RightKeyDown && currentPos < positions.Count - 1){
currentPos++;
}
transform.position = Vector3.MoveTowards(transform.position, positions[currentPos].position, maxSpeed * Time.deltaTime);
}
}
Why are you doing a list of transform btw? Does Vector3.MoveTowards take Vector3, Transform as params?
yknow, inputsystem would make it quite a bit more straightforward
Answered my question wonderful
lmao
😂
the list of transforms is so you can just drag gameobjects in in the inspector
Ok, so it's just so that you actually place gameobjects around, instead of having to manually enter vectors
i'd probably use SmoothDamp though fwiw
if thats ''beginner coding'' then im not halfway of a beginner
There's a time for all ig
it's all pretty basic. if you're unfamiliar with it then it might look daunting, yeah, but that's more about the size i think
it's basic, there's just a lot
if you're curious, feel free to ask
mm i guess it is quite a few basic programming things that a unity beginner might not have had to deal with yet
-# god i hate english
I don't think it would be null
Since you're not passing via indexes, if you don't press left nor right, the reference is empty when reading it at the very end of the update method
You're not doing a direct access to the list, so either set it to List[0] in Start (assuming it exists), or do list access like @naive pawn did
yes I forgot to set it to the first transform in the list my bad
Also the way I'm checking if the number of T is in bounds would technically work, but checking it the other way would be better
You're also grabbing the transform from the list by doing list[i].transform, whereas the list is defined as List<Transform>
yes because I'm assigning CurrentSpot
it would, but you did also write it wrong
Yes but CurrentSpot is of type Transform, and List<Transform>[i] returns an existing transform
I'm also confused with int >= Transform (T >= Spots[0])
yeah that should be T > 0
oh actually, dec your method wouldn't work
you would need to inc/dec after the bounds check
Overally both methods look alike, one uses a tamper variable (CurrentSpot) whereas the other does not
Also yes
why would subscripting a list of transforms give an int
I just wrote it off the top of my head, so I must have gotten confused
Yeah ig that's just it, as said both ideas are the same in the end
i mean, how else would you make it
fixed the mistakes, now it should work
other than using inputsystem and having a different flow to begin with
the bounds checks are incorrect
you would allow T = -1, Spots.Count, Spots.Count+1
(btw typo'd Currentspot in Start and declaration of Spots is still wrong)
sorry im treating this like a code review session now lmao
if we keep going it's just going to turn into my snippet with a few changes since i based mine off of yours lol
Hello! I'm very very new to coding and I'm trying to make it so that if the "Player" has picked up a "Match" and collided with the "Fire" then a sliderTimer ticking down will reset to it's max value, but I don't know how to go about that.
I tried a couple different ways to create statements using "if () && if () then ()", but I keep getting error messages related to my syntax so I think I am fundamentally missing a step in order to create this system
Here is my timer code:
https://paste.ofcode.org/cEyqV4d34tpJWTayNkSBfd
Here is my match code
https://paste.ofcode.org/3USPeMntG8WpdVTW7mVpS3
Here is my timer code where I tried an if && if then statement
https://paste.ofcode.org/XYXkbDLHV8TLrwJe4K6dtf
I would appreciate any help or guidance and if there's anything else I should clarify in order to make my question more understandable please let me know! :)
the fundamental step you seem to be missing is understanding C# basics so I suggest you learn them
Combine conditions in if statements with && and || inside the if statement. As in: if (a == 2 && b == 3)
"Inside" means between the parentheses
this is the kind of question that should have just been googled -> C# if