#💻┃code-beginner
1 messages · Page 589 of 1
Yeah so you should use Debug.Log(“here’s what I want to show in the console”);
For example when you call Jump, in the first line in the function you could put Debug.Log(“Jump”);
If that never prints then you know the function call failed
in the jump function or the place where it calls it
Up to you, but if you put it in the function then it will print every time the function is called successfully
Wherever you want it to print
i want it to print whether grounded = true or false right before it calls the jump function how do i do that
Well since you’re checking in update it will spam unless you gate it somehow
you'd print grounded right before it calls the jump function
you could just enable Collapse in the console
True
You can just do the Jump print I mentioned. You can then use reasoning to infer that if it never prints: Jump is never called
If Jump is never called, that means grounded is always false when you check for input
Because that is the condition you wrote
noone told you to use Console.WriteLine
i didn't blame it on anyone
that's for bare c#, unity doesn't take that
what happens if you google this exacts words
I told you exactly what to write and where
what i mean is; why did you use that, instead of the Debug.Log that everyone told you to use?
Here
cuz when i did it it just gave me errors
Where did you get Console.WriteLine from. Everyone here told you how to print something in Unity
Debug.Log throwing errors? I gotta see this..
like ts
aint no way this would ever throw an error, you're mistaken
ok, ask about that instead of trying something random
https://xyproblem.info
At most you'd get ambiguity error
(i'd guess it was placed wrong...)
or that
WE already told you 😭
I mean, they could have made a class named Debug that doesn't have a function named Log
That would cause that line to throw an error
oh the if doesn't have braces, so putting the log where the writeline is now would call Jump every frame lmao
Or they did using System.Diagnostics as nav implied
But actually saying what the error is would be a good idea
I'm at the edge on my seat.
please do not your seat
phrasing!
therelol
thank you
Well he was met with a dog pile
But yes Mr. E please show your code with the Debug.Log and the error that comes from using it
yes cuz this channel is titled beginner for beginner concepts you don't just give a book to a 3rd grader and expect him to write a written analysis
analogy kinda sucks but i couldn't think of a better one
Otherwise what you’ve said makes no sense
its perfectly fine, no one is faulting you for it.. We just guessing because you haven't shown us , what else can we do but speculate
kind of are
It’s because we love you and want you to succeed ❤️
are you goign to show us? we'd rather not argue about it wont help anyone
i forgot what it said i put it right before the jump this time
and it worked but idk where i'm supposed to find the results
wdym you forgot what it said... just go look and show us
you said it errored, we just wanted to see which error is it and where you put the code
in the console window in Unity
Did you run the game and try to jump or whatever
yes it doesn't work
ok so show us where you put the log
congrats this is called debugging! you found out that this part of the code doesnt run, now you can continue trying to fix it
dammit..unconfigured iDE..
oh gosh - well now because you're not using braces for your if statement you've also made it so jump runs every frame as well
So, the log isn't printing because the if condition is never true.
Also, you're calling Jump() every frame now, it's not part of the if. You don't have any braces
you really need to use { } for if statements in C#. It's not Python.
Yes if you put line breaks in your code for a single block you need to wrap that into {}
well more the ; that matters but yea
i js followed some guy's tutorial and this happens
and what happens?
whatever ur saying about braces
Anyway you actually need to stop everything here and get your IDE configured
i mean you don't need to
(no that's not how it's decided)
If you want a condition to contain multiple lines, you will need to use braces
if(something)
//runs through if statement - without {} if statement only affects first line under it
//always runs no matter what if statement does
if(something){
//runs through if statement
//runs through if statement
//etc.
}```
@smoky river
I know I know. Technically semi-colon. But a semi colon is indicative of a line break.
what's more appropiate for combat system: Duplicate an already existent hitbox object from the hierarchy or instance it entirely via script?
that's not really it either
Neither - Use an Object Pool to re-use a set of existing hitboxes in new configurations as needed!
Object Pooling is a great way to optimize your projects and lower the burden that is placed on the CPU when having to rapidly create and destroy GameObjects. It is a good practice and design pattern to keep in mind to help relieve the processing power of the CPU to handle more important tasks and not become inundated by repetitive create and des...
object pool is godsent
Alright this might be news to me then. LMK. After OP’s problem is solved.
Hi I'm new to C# (I have limited experience with python), I wanted to ask
what do you call stuff like these? operators?
it's basically grouping?
methods ?
there aren't any operators there. do you mean methods/functions?
Which stuff? Operators are symbols that do things, in your screenshots, there is an operator: .
. dot technically though but yeah
It saves time having to spawn new copies of things by keeping the old ones around and just turning them off when they're done. Then you can move them to where they need to be and re-activate them
I'm not sure, I'm trying to figure out all the terminology (my english is not good)
different languages define it differently lmao 
it's so hard to remember what languages consider it an operator and what consider it just syntax
Which thing, specifically, did you want to know the name of?
i'm here to find the reason its not working and the solution
Actually decided I don't have the patience to teach programming from first principles to someone today.
Well, right now, the reason it's not working is twofold:
- Your if statement is never true
- Your jump function isn't in the if statement
like calling a random and range is this code
Random is the class, Range is the function
you will pretty much learn alal this stuff as you do the c# course or check out the manual
aaah I see
Okay, so Random.Range is a method. Which is also known as a function. Technically, a method is just a function that belongs to a class, but since every named function in C# is a method, some people use them interchangeably
I thought functions and methods are only void/int/strint exmaple(){
}
that's a method declaration
it's still a method when you call it
somewhere in the source code, there's also int Range(int begin, int end) {}
long long way to go for me lol
access modifier | returnType | methodname | parameters
private void Method(int number){
thats defining though
Yes, and somewhere inside of unity's Random class is public int Range(int start, int end)
Type MethodName(Type param) -> method declaration
MethodName(arg) -> method call
MethodName itself is the method
ooooh perfect
now I see
alright, thanks for the explanation guys, that was fast :D✨✨✨
for what I've understood of this, it renders a certain amount of objects at the start of the game. But idk if this's gonna work well with what I need as the player can deal as many punches as he wants during the gameplay
rendering has nothing to do with it
How many punches can the player deal at once
how's the jump function not in the if statement
unity object pooling doesn't even prewarm so does nothing in the start of the game
pooling kicks in when the capacity limit has hit
if applies to the thing directly behind it
if you have {}, that means it's a group, the if applies to the entire group
but if you don't, the if applies only to the statement directly after the if
so I make a pool with only 1 object, as the players lands 1 punch at once?
Why "duplicate" it if there can be only one? Which you could move around instead
by behind do u mean whichever comes first
oooh now I understand it, it substitutes instancing and destroying by activating and deactivating
correct
cool
object pool is like a bucket of tennis balls, once you done throwing all the ones in bucket the oldest wants to come back in the bucket ready to be thrown again
not sure what you mean by that
really cool, ty guys
i get it now but it says invalid expression term{
you have to show what you write and not keep it so vague..
show your current !code please 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
we can't know whats wrong if you dont show us
a configured IDE should also be your priority since yours is not configured @smoky river
the errors aren't underlining in your IDE you need to fix that
Because, as we have said multiple times, and as is said in the documentation I linked you, you don't have braces
what do static variables do?
So, if you can only ever have 1 punch out at a time, you'd just re-use the same hitbox whenever you punch
your IDE is not configured
specify what you mean by braces and where
please attempt to learn how to use C# instead of just guessing randomly
it should be lit up with Greens and yellows
I fucking did
!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
@smoky river
takes too long i have no patience
i don't feel like reading
note its required to get help here technically..
it
it will vastly improve your experience by giving immediate feedback
Then fuck off
you gotta read to learn
its also part of #854851968446365696
i'll just ask chatgpt for the error and make it actually help me with the code
we aren't gonna just copy+paste everything in the tutorials to you

Hoo boy are you gonna feel silly when it turns out chat gpt also outputs text and you have to read it
But sure, go do that, just stop wasting our time here

be mindful of peoples free time goddamit. Wasted all this time just to get a response a 6 year old gives
"I'm not doing it nuh huh"
child then go away
can someone help me i want to change scene in my unirt projectg but i cant here is my code:using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.SceneManagement;
public class SceneManager1 : MonoBehaviour
{
// Start is called before the first frame update
public void SceneChanger()
{
SceneManager.LoadScene(1);
}
}
i created empty object
!code
then
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 cant, why ? you have to explain..
ok
SceneManager1 this is a horrible name , try to stick away from already taken names by Unity API
okay so whats happening instead?
nothing
@edgy tangle
control flow statements if, if/else, for, foreach, while, do..while take a single substatement as the body of control flow statement
so for example, if has the form "if ( cond ) stmt"
{ } is a special statement, the block statement
it takes several substatements and runs them in order
so when you provide a block statement to if, the if just sees that single block statement as its scope
if it's not a block statement, no real difference, if just sees that statement as the scope instead
; is also a special statement, the empty statement, it does nothing, if (x); doesn't do anything even if x is true (assuming the condition doesn't have side effects of course)
this also means that if/else if/else technically isn't a construct of its own, it's just an if/else nested inside another if/else
switch and try..catch..finally have the braces as part of their syntax, rather than using a block statement, so you can't use single statements for those (i mean, obviously not for switch)
so put a log inside to see if the button is calling the function
Why should something happen?
yeah i want to change scene
i will try
if not most likely you either configured button wrong, or dont have event system
i hav eevent system
okay so more reason to log the button click
A tool for sharing your source code with the world!
hit save then send link
I mean to ask you, why should the scene change when the button is pressed
What have you done to make the button interact with the script
show that you linked it in the inspector correct?
how can i show you
i did it
screenshot the button component and its inspector
You made an empty method that just lives in the void
that aint the button is it..
this is the empty object
if you have an event system, check out the inspector during play mode for it, pullup the info box, it should show you what you are hovering over
if you have other UI elements its likely they are getting blocked
sorry
how
I believe Buttons don't work with a Sprite Renderer
They'd have to have an Image as the Target Graphic
just like I said, Pullup the Event System during PLAYMode you should see a black bar at the bottom click it
Sprites are not meant for UI
Button component is for UI, not for a SpriteRenderer, which is for a 2D GameObject . . .
so if i changed it it should work?
Which of these two objects has your button component on it
By creating a new Button game object, you'll get one that's set up with the correct components
(Not a new Button component)
you can use the Drop-down menu in the editor to create a UI Button GameObject . . .
you cant put a button on anything but UI elements
raycast wont detect the area outside of canvas
so what to do
create a button ?
Create a new Button from the gameobject menu, as pointed out
ok wait a sec
after that Ideally your raycast will finally hit it, unless you made the Text objects be above by accident
Show your button's inspector
that's the same button
literally did nothing diffeent lol
mb
we told you to make a new one properly using UI
So then why did you show us the same button again
Right. But isn’t this just a long winded-way of saying: for if statements: if you’re only running a single line (whose line break is indicated by semi-colon), you don’t need curly braces around the content to run when the condition is true, but if you have multiple lines (whose ending is indicated by a semi-colon) then you need the braces….?
I do appreciate the additional info tho
BTW
THANK YOU
IT WORKED
but not
i mena the scene changed
but its one of the things there
wut?
Does that scene have a background and buttons
idk why
the code changes none of that
it had everything there
if the scene is like that then you had it like that
or you're swithicng to the wrong scene
then you did not save?
I DID
things dont magically disappear
Hi, I created this interface called ITimeTracker, but when I go to link it to another script the option for my interface isnt there. Does anyone know why?
BUT NOW ITS GONME
then you're loading the wrong scene
stop with the caps . . .
your !IDE is not 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
first of all configure your IDE
get your !ide 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
double smackk
see
also please chill out with the vertical messaging
for the game im creating, i have it where if the player collides with this power up prefab, it should spawn a clone of the player but for some reason whenever the powerup is collected, the game freezes.
the clone does spawn so idt thats an issue; i think it might be somehting to do with how i assigned the player game object in the inspector. I made my player object a prefab and assigned that prefab in the inspector of the clonecontroller powerup cuz i couldnt assign the actual player game object from the hierarchy. lmk if you want me to explain something for a better understanding
btw the debug.log for the player position does show up in the console
CloneController script: https://paste.ofcode.org/?edit=PWZBREhxXJFGSEvWL2sPNW
PowerUpClone script: https://paste.ofcode.org/zTLwgWjaEtLjjHm6VR5T27
Because you put it there
If it's crashing that's probably infinite recursion
you probably have a loop somewhere that runs a method over and over . . .
Show the inspector of the clone prefab you're instantiating
my point is, you shouldn't care about lines. the language doesn't; it cares about statements
and this is the inspector of the object that is instantiating it
What calls ApplyPowerUp?
when you say it is "freezing" are you referring to the entire unity editor becoming unresponsive to input, or does only game mode stop working? because those imply different things
so for the powerup to be granted the player has to answer a question that pops up. should i share that scipt?
no the unity editor works fine as im able to move the joystick around but the game is frozen excluding the joystick
then you have an error that you are ignoring and you just happen to also have error pause enabled
Okay, this is a different problem than the one I was investigating. Can you send a screenshot of your entire Unity window, after the clone appears and the freeze happens, with your console visible?
actually wait, if your in game joystick is working that's not even the case. the game isn't freezing, things just aren't working the way you expect
here
like whenever I click onto my game screen, the joystick pops up as intended but nothing moves around mb for using the word freeze
Okay, no errors, ClonePlayer exists... I don't think the cloning process has anything to do with this issue
yea but it only happens when i collide with the cloning powerup
hold on lemme try something
That's good. You know where the issue comes from . . .
Is everything else working as expected, just not movement?
let me try recording a video cuz idt im explaining it correctly
while we wait for this video i'm gonna go ahead and guess that timescale is getting set to 0 or something
hold on i moved my scripts to a different folder now its giving me random errors lemme try fixing it first
nevermind
i fixed it
its good now
what ended up being the issue?
im pretty sure i had two scripts on the powerup prefab both of them were interfering with the collecting logic
i removed one of them and it works now
that shouldn't have affected everything else unless it was doing something like setting timescale to 0 🤔
I'm doing a combat system but when I land a punch the console says: "NullReferenceException: Object reference not set to an instance of an object" https://paste.mod.gg/ioiahwxjfaci/0
A tool for sharing your source code with the world!
what line
21
Then hitbox is null
but I have a parameter assigned to Hit method when I click, so this parameter is used to define the hitbox object
and yet nothing named "Punch" exists in the scene
but it does right here
did you bother looking at the documentation for GameObject.Find?
Find doesn't work on disabled objects
oh
Why use find at all? Just assign the reference directly
wdym
like, there will be more than one attack so I'll need to call the same method but with other stuff as parameters
So pass an object reference to the function instead of a name
Fair enough
!docs
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
How do i refrence the camera in a script in a chaacter to transform the camera?
i tired private GameObject = gameobject.FindObjectByTag("MainCamera"); but that doesnt seem to work
Did you log the variable you assigned it to and check if it's null? Also, your code above does not have a variable name . . .
You put it in a field initializer and it's not allowed
Field initializer meaning the place you declared the variable as a class member
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
public Camera myCamera; and assign it in the inspector
or - just use Camera.main which is a shortcut to get the main camera
you'll learn it if you keep it up
So basically when the character collides with a trigger I want it to move the camera to the right
or wtv
So I use ontrigger function
But the collider is refernece how??
wdym?
Why do you need to reference the collider
You're using OnTriggerEnter I thought
hi im trying to get my index onto the self made button but forsome reasone it wont get throw can i get help ?
https://paste.ofcode.org/TfrnKPiX8Wxi5Vxm43VMC7
OnTRiggerEnter gives you a parameter
you would use that parameter
you're confusing class names here with actual references/variables to individual instances
You can think of a class like a "blueprint" for a type of object.
The class describes how the object behaves, what data it holds, and what method are available to run on it
every instance of the class will follow that template
THis is the essentail abstraction of Object Oriented Programming
Oh so the colider is a 2dBoxColider by class?
BoxCollider2D
mhm
All BoxCollider2Ds are Collider2Ds
That depends on the specific settings of your code editor
maybe
It might be that green is all type names
yeah
There are other things that are types that aren't classes
Such as enums, structs, and delegates
If it's an instance of a class, then its type is its class
brain cant comprhened this stuff
i thought roblox scripting could get hard
this is omehting else
cant even compare
Everything in C# is an object.
Objects are broken down into other categories such as:
- Classes
- Structs
- Delegates
- Enums
Lua is a pretty simplistic language compared to C#
The main thing is that LUA isn't object oriented. SO this is your first foray into object-oriented programming
it's definitely a new concept
i though it was object oriented
if Lua was object oriented it would have classes
i thought object orientated means that u work with objects that each have their own methods and properties
yes, which LUA doesn't do
lua has pure functions
and the heirarchy was really easy
if u want to get to any object
u just start form ur workspace
and go through each parent
You're also now conflating LUA with Roblox btw
that is a Roblox thing you're talking about
both of those are also dynamically typed languages
so there's two big different paradigms you will need to get used to here:
- C# is object oriented
- C# is statically typed
Static typing means you need to explicitly say what type each variable is
yeah
in python you can just do:
x = 5
in C# you must do:
int x = 5;
You'll get used to it, then it will become second nature
What doesn't work about it
doesnt log Level1
Is "Hit" being logged in the console?
no
THen the code isn't running at all
Which means you don't have the circumstances in the scene set up properly to get an OnCollisionEnter2D
I thought you mentioned earlier you were using a trigger colldier, is that correct? This won't work for a trigger
That's the 3D verison
you need OnTriggerEnter2D
void OnTriggerEnter2D(Collider2D other)```
also you should add a log outside the if statement as well to make sure the function is actually running
yeah its iside the looped on
one
inside void update
it worked
cold
what i upadtre to
collision is a confusing name for that parameter I would say
it's not a collision, it's a collider
yeah first I had put the script in teh camera
and it tottaly didnt work
realized that the camera doesnt acc collide
Yes it needs to be on one of the objects involved in the collision
yeah then I put in the character now it works
Hey guys, I'm new to Unity and need help translating my animator's equations and mechanics into Unity
if i were to do Random.Range (0,2) would it never actually do a 2
I want to know how to create a rig I can input angles into
it would never do 2
ok thanks
Check thje version of Range that accepts int parameters in the docs: https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Random.Range.html
This is pretty vague. Just a script that has a method on it that accepts an angle and sets its localRotation accordingly sounds like?
Yeah
So did you try that? DId you have issues?
I was wondering how I could make a little human and set pivots on it
I'm completely new and dont know where to start at all
Huh.. so doing 10, 0 would actually give a range between 0 and 10
I play a game called Elite Engineering where you build with mechanical blocks and logic nodes
1 and 10
I built a working animator on there and am trying to remake it
is it possible to test equality on vector3?
of course
usually not a good idea to do it directly though
Bad idea but you're just missing the new in there
if (someObject.transform.position == new Vector3(1, 1, 1))```
yeah whys that bad?
Because for one it's imprecise
it's very unlikely for the position to be exactly that
unless you explicitly set it to exactly that somewhere
what are you actually trying to accomplish with this code?
I don't see why you would need to do such a comparison to do that
to check if the camera is in teh 2nd spot
to move the camera back
to teh orignal
if teh character went backwards
For that kind of thing you would just have e.g. an array or list of camera positions and store an int currentCameraPositionIndex variable or something
to know where it currently is
Or better yet - use Cinemachine ClearShot
In Unity, what's the best way to preserve game state between scene loads? I use a pub-sub system for components to interact but for example, I want the score to be preserved between scenes. I currently use a static class to do this but I feel like maybe there's a better way?
a script on a DDOL singleton object
what you're describing sounds simple at first but very quickly becomes impractical and impossible to write sensible code for.
Well I gotta begin somewhere
real quick, want to load a scene from a file structure, tried calling Load on "Terrain/Simulation" (from the boot scene that would be the relative path)
Idk what Im doing so it is how it is
"./Terrain/Simulation" doesn't work though
either
rather is it possible to not have to use the full absoluite path?
prety sure LoadScene takes the simple name of the scene file, not a path, absolute or otherwise
for my combat system, I'm trying to organize 2 things: The data from the attacks, like damage, cooldown, etc, and the enemies data. How or where I put these stuff?
the full folder structure path does load it as expected
ScriptableObjects probably
https://docs.unity3d.com/Manual/class-ScriptableObject.html
There's no context from which a "relative" path would be relative to
why is this so complicated
why cant I just make a list of strings
string[] list = ("Apple","Banana", "Orange")
how do i do this???
string[] list = { "Apple", "Banana", "Orange" };
ah ok
how can i manualy move to scene in the hierachy ?
wdym manually move to?
like this
i dont want to delete it just like a keybind that let me change the scene to test stuff
even when i do this it wont change scene
you have two scenes open
(set active scene)
just double click the scene file to open it single?
yea i want 2 scene to be open to test stuff
Are you trying to move an object from one scene to another or something?
cause idk what wanting 2 scenes open have to do with
even when i do this it wont change scene
exacly
I think this?I never tried tho https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SceneManagement.SceneManager.MoveGameObjectToScene.html
drag it
I don't understand what you're expecting to have happen here
Note that changing the active scene doesn't really do anything on its own, save for a few things like changing where your environment settings are coming from
Both scenes are still loaded
can i move game object from scene 1 to scene 2 ?
Yes, using #💻┃code-beginner message in a script
But I'm still very unclear on what the actual objective is
especially given this image you sent
if anyone here used the videoplayer component before, quick question
the .frame property isnt updating for whatever reason and i cant seem to find out why? the videoclip is clearly playing and .isPlaying is being reported back and im a bit stuck here
the same happens with the .time property
hi does anybody know why cant i see bake tab? in unity 6000.0.35f
because new Navigation system uses Navmesh Surface component
https://docs.unity3d.com/Packages/com.unity.ai.navigation@2.0/manual/CreateNavMesh.html
btw this a code channel
I accidentally clicked "generate as new type" while refactoring. How does one undo the creation of the namespace within Visual Studio?
Just delete the file that defines it.
Found it in my files. Thanks!
I’m running into an issue with the zombie animation states. Initially, the zombie wasn’t moving in the Update method, so I used a coroutine to fix that. However, after making this change, the animations are now looping continuously between walking and attacking, even when the zombie should be either walking or attacking based on its distance to the target.
I’m using the remainingDistance and stoppingDistance to transition between walking and attacking, but it seems like the transitions are happening too quickly. The zombie switches between these two states without properly completing either one.
csharp
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class ZombieController : MonoBehaviour
{
public Transform target;
private Animator animator;
private NavMeshAgent agent;
private void Start()
{
animator = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
StartCoroutine(UpdateDestinationEvery10Seconds());
}
private void Update()
{
if (agent.remainingDistance > agent.stoppingDistance)
{
animator.SetBool("isWalking", true);
animator.SetBool("isAttacking", false);
}
else
{
animator.SetBool("isWalking", false);
animator.SetBool("isAttacking", true);
}
}
private void TrySetDestination()
{
agent.SetDestination(target.transform.position);
}
private IEnumerator UpdateDestinationEvery10Seconds()
{
while (true)
{
TrySetDestination();
yield return new WaitForSeconds(1f);
}
}
}
so when I write my code, I can't seem to have options pop up like here, any reason why? (tried on monodevelop, Godot C#, and visual studios)
!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 are your animation transitions set up?
My animation transitions are set up like this in the Animator:
I have states for Idle, Zombie Walk, Attack, and Dead
I use parameters like isWalking and isAttacking (both Boolean) to control the transitions between these states.
For example:
Idle → Zombie Walk happens when isWalking = true.
Zombie Walk → Attack happens when isAttacking = true.
Transitions back to Idle or Walk occur when these parameters are false.
I have disabled hax exit time for all
And I have set stopping distance =5
I’d look into it a bit more if I wasn’t busy. My apologies. But a quick comment
If the attack animation is not looping, i.e. just one animation, you can enable has exit time and just set it to 1 (one cycle), then you’ll save a lot of code and conditions, since you can just use animator.Play(“name of animation”)
Also there’s an animation channel
Thanks for the suggestion! The attack animation is looping, so I rely on conditions to handle transitions. I’ll try using Has Exit Time where possible and look into animator.Play() and the animation channel. Appreciate the quick help!
Hello! My problem is: https://streamable.com/2nt3jc
I'm a beginner, and I've been struggling for about 1.5 hours trying to get it to work properly.
are the wheels colliding with the vehicle body?
if so, make sure to make the wheels have there own layer, then exclude that layer in the vehicle body collider
The wheel colliders stay where they should, but the wheel meshes don't go to the correct positions.
thats really strange
try having empty game objects where your wheels are, then making your wheels children of the empty game objects (like wheel holders for each wheel), then change the UpdateWheel function to set the local position to 0 0 0, and then change the local rotation for wheel spinning. I think something like this:
void UpdateWheel(WheelCollider col, Transform trans)
{
Vector3 position;
Quaternion rotation;
col.GetWorldPose(out position, out rotation);
trans.localPosition = new Vector3(0, 0, 0);
trans.rotation = rotation;
}
you may need to modify because im lacking on sleep but, thats what i think it is
Thanks, i try that.
👍
hello- im currenlty trying to do code to where when i hit a few keys, the light should change?
i cant seem to get it to show up in the game window, and my code isn't showing up w any errors like reference
what are you trying to change with the light? Can you show me your code?
this is jsut the turning on and off part
some other parts of my code work with diff keys, like dooming in and out, and changing the cube's color texture randomly
the light parts are giving me trouble
some of this code was given by our prof, but the rest was up to us
the script is atatched to a gameobject with the light assigned to the spotlight variable yes?
what part?
are you getting debug logs when you press q?
i should say the code also seems to be able to change the color but it never becomes visable-
actually.. no
it doesnt even wanna turn off after i hit Q again
me neither
try this:
if (spotlight.enabled == true)
{
spotlight.enabled = false;
Debug.Log("Disabled");
}
else
{
spotlight.enabled = true;
Debug.Log("Enabled");
}
ty
replace this with the code i provided
like this?
yes
add another fence at the end to make a codeblock
mybad
nothing, only message i get is Enabled
lack of sleep..
this kind of logic is quite unnecessary
i donto know if the light is working-
did the light get enabled?
just trying to debug.. im no mastermind
well apparently in the logs it did but i still odnt see it
try turn it on in the editor
i think maybe the directional light might be the only one activated in the scene
do you see it enabled if you check the component directly?
it's a component, right?
sorry im like. half asleep and its 1 am and i need to get this done b4 10 am
the checkbox beside the component name is the enabled state
no, that's for the gameobject
that's the active state for the gameobject
spotlight is a Light component
this part?
yeah
yes
its enabled
always was
are you sure that's the right object though
it says here that you've assigned an object named Spot Light
you showed an object named spotlight
ah, ok.
still reads in the code
hold on, spotlight also has a LevelController?
ok so you have 2 LevelControllers
suppose the light is currently on, and you press Q
one of the LevelControllers toggles it off
the other toggles it back on
But he/she changed the script not?
it's still doing the same thing
(they, he is okay too)
okay so i removed the script from the spotlight
does it work now?
do you see the Light getting enabled/disabled?
in the inspector, i mean
ill try to get a video, my obs is bugged out so it will be on my phone
ok
can you just answer this please @sick valve
yes
yeah i can't make out any detail there
yeah i see it changing
shoot
does that tick icon change when you press q
yes
can you even see the light in the editor?
dont think so
probably the issue
im not sure enabled has the effect, so just to check:
while in edit mode, go to game view, and try enabling/disabling the light component, see if that makes any difference
if not, try deactivating/reactivating the gameobject, see if that makes any difference
once u get the light to be visible in the editor, try run the game again
this is scene view, not sure lighting stuff is gonna show up. check the game view
........ howwww do i do that
enabled works for me
change the values of the light component
could you please point it out im dumb
all these stuff (mine is different cause i have a different light source)
And what if you change the gameobject active state and not the light?
@sick valve if you're getting the enabled/disabled state correct now, this is out of the scope of this channel. try asking in #archived-lighting or #💻┃unity-talk.
maybe try creating a new light in the scene, move it to where you can see the light in effect, change the "spotlight" variable to that new light you created and try in game then
sorry ^^;
no need to apologize, just pointing to places that might be more helpful 🙂
lolll, it was just because they had the wrong settings on there light component. Cant wait for someone to help me with my code 😭
@sick valve btw, your old enabled = !enabled was fine, you don't need the if..else on spotlight.enabled
yeah, my janky code is useless
it's not janky, it's just the same thing but longer lol
yeah..
but i'd recommend the x = !x form, it's clearer in intention
yeah, i just didnt know about that untill now
enabled =^ true; if you like to live dangerously
^ works on booleans?
I saw it in an old video, apparently
oh, c# also allows |/& on booleans, so i guess not that surprising
just not used to it lol
......huh.....
https://dotnetfiddle.net/MwrTvN Slight change in the syntax. It's ^= and not =^
Don't ask me why it works
ah yeah was wondering why that felt off lmao
i know why it works, it just feels like it shouldn't.. initially, at least
but..
c/c++ also do, because bools are ints
java also does
js also does, because bools can be coerced to numbers
just ~ that generally doesn't work
is someone pro enough to help me in #archived-code-general ..
no one has helped me 😦
They will help you when they get the chance, don't crosspost
mybad
Anyone got experience with Vault Inventory package?
Does it work properly? Is it easy to adjust/extend to my own needs?
This isn't the channel for such questsions.. but you're also not likely to run into anyone who's used it. Read the reviews and contact the publisher with any specific questions.
guys I'm studying Scriptable Object, but I'm not understanding how I'm supposed to handle multiple objects data, like enemies. For what I'm analysing and testing here, it seems to handle just a single enemy's data per script. If I have 2 or more enemies in the scene, what do I do?
A ScriptableObject is an asset file, that uses the script.. create multiple SO's
why when I set the transform position of one object to 0,0,0 does it not match the location if I do the same with another object?
but I can mess it a little to make a class or a list so I keep all the enemies' data in only one asset?
its a data container you can store whatever you want, only serialization limits you
I mean you could do that, but the point of SO's is that you have multiple of them and each enemy has it's own SO
with no information to your situation and what you're doing to go off.. first guess, you're setting the local position of a child to 0,0,0 and each parent position is different
does on trigger 2d only check if the parented collider is touched or how can I check a different collider from a different game object
- your own object
Or - child objects if you have a Rigidbody
Ok, so... this pretty much a question about AI navigation, but... pretty sure I am gonna have to mix with some code, so I am gonna ask it here. How could I, make it so entites consider a thing an obstcle, but only if certain conditions are met? And the tricky part, is this is not in an on/off the obstacle, I want the obstacle to be there and considered by everyone as an obstcle, but if I for example tell one particular entity to move INTO the obstacle to ignore it complitely while it is still active for everyone else
Are you using navmesh?
Yeah
You can use navmesh areas and set rules differing for each agent are you familiar with navmesh at all or?
Not much, but I knew that. Just that they... kinda have to remain as the same type of agent?
Yeah you can tweak how they interact with navmesh with layers or tags to specifically set which gets considered as an obstacle or not I think code monkey had a video on navmesh id recommend giving it a watch
If you still need help tomorrow I’ll help you with it when I’m home
So the idea is. Blue-ish dude bad guy, he can ignore the obstacles (Red area), Green guys are good guys, they consider the red area an obstacle. I want to the have the liberty of tell some, but not all Green guys to move INTO the red area if want them to, but not ignore ALL red areas (there may be more than one)
You want to set it or you want it to be randomly assigned ?
Most areas are supposed to be randomly generated
You place waypoints before the areas are placed. I want to make it so some waypoints tell them specifically to move into the area to get into it
But also consider not all waypoints affect all Green guys at the same time, they might just affect a bunch
I kinda have the feeling that by that point I am gonna kinda just have to tell the object to move towards the waypoint manually and disable the navmesh agent temporally...
Can I send screen recording here , I,m stuck with this problem for 2 days and cant find any solution as I'm new to this.
If you want the green guys to move into some of the red areas, you need to place them (red areas) in a collection, and for each green guy, choose a random number based on the collection count to get the total number of red areas they can enter. create a collection on the green guy (using the previous random number as the size), and randomly select from the red area collection until the one on the green guy fills up . . .
sure, use streamable . . .
So... I randomly select areas from a collection until the one I want shows up?
I’m running into an issue with the zombie animation states. Initially, the zombie wasn’t moving in the Update method, so I used a coroutine to fix that. However, after making this change, the animations are now looping continuously between walking and attacking, even when the zombie should be either walking or attacking based on its distance to the target.
I’m using the remainingDistance and stoppingDistance to transition between walking and attacking, but it seems like the transitions are happening too quickly. The zombie switches between these two states without properly completing either one.
csharp
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class ZombieController : MonoBehaviour
{
public Transform target;
private Animator animator;
private NavMeshAgent agent;
private void Start()
{
animator = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
StartCoroutine(UpdateDestinationEvery10Seconds());
}
private void Update()
{
if (agent.remainingDistance > agent.stoppingDistance)
{
animator.SetBool("isWalking", true);
animator.SetBool("isAttacking", false);
}
else
{
animator.SetBool("isWalking", false);
animator.SetBool("isAttacking", true);
}
}
private void TrySetDestination()
{
agent.SetDestination(target.transform.position);
}
private IEnumerator UpdateDestinationEvery10Seconds()
{
while (true)
{
TrySetDestination();
yield return new WaitForSeconds(1f);
}
}
}
You said the green guys can enter some red areas, but not all. I figured you wanted the chosen areas to be random. If not, then you need to specifically select the red areas from the collection and place them in the collection on the green guy . . .
No, the red areas the Green guys can enter are definetly very specific
So.... I place the áreas on a collection, and... I could maybe determine which one they want them to able to enter, now what I do with that?
Then you should place those areas in a collection to have access to them at any time . . .
How do you determine which one they enter?
Ah... I guess I could do something like... if the waypoint you are trying to reach is colliding with an obstacle, add that obstacle to the collection of obstacles you can enter?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
guys can anyone help me with this
the script doesn't have error i even try test playing it and working fine until i open the script
it said i'm having error on onClick
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
public class StatManager : MonoBehaviour
{
public TextMeshProUGUI valueText;
public TextMeshProUGUI modifierText;
public Button increaseButton;
public Button decreaseButton;
public int currentValue = 1;
private int maxValue = 30;
private int minValue = 1;
private int stepValue = 1;
public event Action OnValueChanged;
private void Start()
{
UpdateValueText();
increaseButton.onClick.AddListener(IncreaseValue);
decreaseButton.onClick.AddListener(DecreaseValue);
}
void IncreaseValue()
{
if (currentValue < maxValue)
{
currentValue += stepValue;
UpdateValueText(); OnValueChanged?.Invoke();
}
}
void DecreaseValue()
{
if (currentValue > minValue)
{
currentValue -= stepValue;
UpdateValueText(); OnValueChanged?.Invoke();
}
}
void UpdateValueText()
{
valueText.text = currentValue.ToString();
UpdateModifier();
}
void UpdateModifier()
{
int modifier = GetModifier(currentValue);
modifierText.text = modifier >= 0 ? "+" + modifier.ToString() : modifier.ToString();
}
public int GetModifier(int value)
{
if (value == 1) return -5;
else if (value <= 3) return -4;
else if (value <= 5) return -3;
else if (value <= 7) return -2;
else if (value <= 9) return -1;
else if (value <= 11) return +0;
else if (value <= 13) return 1;
else if (value <= 15) return 2;
else if (value <= 17) return 3;
else if (value <= 19) return 4;
else if (value <= 21) return 5;
else if (value <= 23) return 6;
else if (value <= 25) return 7;
else if (value <= 27) return 8;
else if (value <= 29) return 9;
else if (value <= 30) return 10;
return 0;
}
}
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
What’s showing in console ?
'Button' does not contain a definition for 'onClick' and no accessible extension method 'onClick' accepting a first argument of type 'Button' could be found (are you missing a using directive or an assembly reference?)
You wrote your own class named Button and it's using that instead of Unity's Button class
idk man everything was fine i just woke up and open the project and test played it everything was still fine until i open the script and suddenly it got error 💀
Cool, but the problem is you wrote your own script named Button
i haven't even touch the keyboard
wait lemme go check
hey guys so just a quick question i wanna make or atleast try to make a game similar to my fav franchise monster hunter any good melee combat vids to get started on
Otherwise the error would be saying UnityEngine.UI.Button does not contain...
Sure, if that's what you need. We don't know the reason they can enter specific red areas (obstacles). Only you do . . .
Well, the reasons may vary, is just something I want them to be able to do
Since the player is supposed to command them in very various ways, so that is something they may want or may want to avoid
But the question is, what do I do once I have the obstacle I want them to ignore?
i checked that and no i chose the unity one and error is still one
How did you "choose" the unity one?
When you mouse over the word "Button" in your script, what comes up? Where does it go if you right click the word Button and "jump to definition"?
i retyped it and when i checked it it show the Unity.Ui and stuffs
okay nvm as soon as i checked that
That disappear and now there's no button
Only Button Editor
How about instead of us playing 20 questions next time you just post the error directly
sorry 😭
How do the minions (green guys) move? Do they already avoid the red obstacles? If so, how did you set it up to avoid them?
The red areas are just obstacles on a 2D NavMesh, I bake it after they spawn
I’m running into an issue with the zombie animation states. Initially, the zombie wasn’t moving in the Update method, so I used a coroutine to fix that. However, after making this change, the animations are now looping continuously between walking and attacking, even when the zombie should be either walking or attacking based on its distance to the target.
I’m using the remainingDistance and stoppingDistance to transition between walking and attacking, but it seems like the transitions are happening too quickly. The zombie switches between these two states without properly completing either one.
and here's the code below
https://paste.mod.gg/gyoteqsqcdqt/0
A tool for sharing your source code with the world!
can you guys help me with it, i'm stuck here for 2 days and cant find any solution as I am new to it
Then we have to figure out how to update the navmesh to remove and include obstacles during runtime . . .
That's just clearing the NavMesh and baking it again right?
thanks guys found the error
the " Button " automatically changing to the one in the trash for some reason instead of UnityEngine.UI one
sorry for the trouble
Don’t apologise that’s literally the point of this channel but just send your console when you have an issue
anyone please?
Your code won’t load but have you tried to just add a buffer between the states
can you explain a little ?
Are you on mobile by any chance? paste.mod.gg links don't work for me on mobile
Or it goes into a blank editor when i try to scroll
You can add like a +0.1f buffer/delay between the states so they don’t spam switch
Okk let me try it
hi im trying to reduce the alpha of this sprite everytime i click but it isnt working. heres my code and my error
spriteRend.color.a -= 64;
"Cannot modify the return value of 'SpriteRenderer.color' because it is not a variable"
you have to extract the color out to a variable and reassign it
Color color = spriteRend.color;
color.a -= 64;
spriteRend.color = color;
though, that 64 is probably wrong
color.a is between 0 and 1, not 0 and 255
to reduce it by a quarter, you'd have to do -= 0.25f

SpriteRenderer.color is a property, so you're actually calling a function when you access it
Since it returns Color (a value type), you're trying to modify the copy that the function returns
hence the error
it is, indeed, not a variable!
it's kind of like trying to write 3 = 5
ohhh okay i see
they may want to clamp the value to be sure not to go below zero or something invalid
color.a = Mathf.Clamp01(color.a);
its working now, thank you for the help and extra info! ^ ^
consider...
Color color = spriteRend.color;
color.a = Mathf.MoveTowards(color.a, 0, 0.25f);
spriteRend.color = color;
i don't think that'd be an issue considering the previous bugs reported
255 was treated as 1, so -0.25 should be considered 0 as well
or that ^
Probably, give it a try. I haven't messed with it before . . .
no it didnt work
This is more of a syntax query. I have a PoolableScriptableObject<T> with a property of type T. Does it make more sense to name the field Item or Value?
var prefab = PoolableScriptableObject<T>.Item;
var prefab = PoolableScriptableObject<T>.Value;
No idea man it sounds like it’s between both states so maybe adjust the buffer I can’t see your code for some reason it just won’t load is the attack always playing and they’re just switching between or is attack only playing once ?
I use Value for wrappers, Item for collections.
T is a C# object. It represents the actual prefab to be pooled. A ScriptableObject is used to store the C# object like a prefab just as you would store a GameObject in the project folder . . .
Item definition:
an individual article or unit, especially one that is part of a list, collection, or set.
using System.Collections;
using UnityEngine;
using UnityEngine.AI;
public class ZombieController : MonoBehaviour
{
public Transform target;
private Animator animator;
private NavMeshAgent agent;
private float stateSwitchCooldown = 0.1f;
private float lastStateSwitchTime = 0f;
private void Start()
{
animator = GetComponent<Animator>();
agent = GetComponent<NavMeshAgent>();
StartCoroutine(UpdateDestinationEvery10Seconds());
}
private void Update()
{
if (Time.time - lastStateSwitchTime >= stateSwitchCooldown)
{
if (agent.remainingDistance > agent.stoppingDistance)
{
// Zombie is walking
animator.SetBool("isWalking", true);
animator.SetBool("isAttacking", false);
}
else
{
// Zombie is close to the target and should attack
animator.SetBool("isWalking", false);
animator.SetBool("isAttacking", true);
}
lastStateSwitchTime = Time.time;
}
}
private void TrySetDestination()
{
agent.SetDestination(target.transform.position);
}
private IEnumerator UpdateDestinationEvery10Seconds()
{
while (true)
{
TrySetDestination();
yield return new WaitForSeconds(10f);
}
}
}
heres the code
between those 2? probably Value, but imo neither are particularly ideal for something that seems to be standalone
okay, that make sense. I'm trying to find terms to use consistently across code, and this is definitely wrapping the C# object to store it as a prefab . . .
the prefab would then be instantiated to create the pool, right?
what about Source?
Is this a getter to get an item from the pool?
no the two animations are just looping one after another
Oh you said it's a field, so a static field?
damn, I do like that one. Now it's Value or Source, lol . . .
Reduce the coroutine time it’s probably not updating enough
Element?
Just half it and see
Can i still read the linear and angular velocity of a kinematic rigidbody when im moving it with transform? Or do i have to rely on implementing it myself with (currentPos - lastPos) / period;
No, it's a property on a ScriptableObject. I want to pool C# objects. Storing the C# class on a script to use as a prefab works (and exposes it in the editor) but what if I want to re-use that same prefab?
Using a ScriptableObject with a field of the C# class allows me to make prefabs just like dragging a GameObject into the project folder . . .
That's what I used for collections . . .
How do you clone a generic C# object? (question to RandomUnityInvader)
yup , that fixed it , thanks a lot
So this property is the instance of the C# class that will be cloned when you get an item from the pool?
Or am i still not getting it
No worries man
I just use this and create a derived class for the C# object. Then use the SO as the prefab in my ClassObjectPool<T> . . .
public class PoolableScriptableObject<T> : ScriptableObject where T : class, IPoolableClass<T>
{
[field: SerializeField]
public T Value { get; set; }
}
public class PoolableBullet : PoolableScriptableObject<Bullet> { }
Ah okay I just read this - I also like Source here
Prototype would be appropriate.
or Template
That would make it very obvious that it is the blueprint, rather than a copy
Yes, this class is used as the prefab and clones of it are created for the object pool . . .
Still don't understand how you use the serialized value. It's not like you can use Object.Instantiate, so how do you create duplicates of this source value? Or are you instantiating the scriptable object itself?
If you're instantiating the scriptable object, Source doesn't make sense to me, because only the original SO will be the source. The duplicated SOs will then also have a field called Source, which doesn't make sense.
you should avoid using the word "prefab" here, because this is not a prefab
I presume IPoolableClasas has a "Clone" method on it
@brave compass That's true, and if that's the case, you could just directly clone the C# instance without having to clone the whole SO
anyone?
JsonUtility would provide the same functionality as Instantiating the SO
Ah, so you are instantiating the entire PoolableScriptableObject<Bullet>?
In that case, Value would be a reasonable name
We don't know yet!
I am rather confused here
No, velocities will be zero if you're only changing the transform.
gotcha, thanks
@swift crag No, I am not Instantiating the SO. ClassObjectPool<T> has a _prefab field which is set to PoolableScriptableObject<T>.Value when the object pool is initialized. To initialize the object pool you must provide an event for public event Func<T,T> Created. E.g., for a bullet object I'd pass in cs private static Bullet CreateBullet(Bullet bullet) => new Bullet(bullet);
The Clone method would invoke the event
private T Clone()
{
Debug.Log($"Creating new object of <color=yellow>{_prefab.Value}</color>.");
return Created?.Invoke(_prefab.Value);
}
Okay, so a few things I'd change
PoolableScriptableObject is a misleading name. The scriptable object isn't poolable!
It looks like a PoolableScriptableObject<Bullet> is just a way to store a Bullet. Perhaps PooledObjectTemplate<T> would be better?
I get that. I used ScriptableObject because that is the asset I'm passing in . . .
the asset you're passing in?
You drag the SO in the prefab field of the ClassObjectPool<T> . . .
Ignore ObjectPool (up top), that's for actual Unity objects). ClassPool is for C# objects . . .
You are not instantiating a PoolableBullet. You are cloning some object that's stored in the PoolableBullet unity object
Your names should make it clear that this is a container for an object
PoolableBullet also implies that this thing is a bullet, and that it's poolable
neither of these things are true
Yes. That's what I'm working on (asking) now. I want better naming conventions for this . . .
So I'd go with:
PooledObjectTemplate<T> : ScriptableObject // (plus the constraints on T)
BulletTemplate : PooledObjectTemplate<Bullet>
Item, Value, Source, Element, Template, Container, etc. Generic stuff that represents the object itself and what contains the object . . .
what about PoolableObjectTemplate? PooledObject sounds like it already happened (exists), and able depicts it can be pooled/used for pooling . . .
That's reasonable, yeah.
oh, wait, so was Value considered the appropriate name for the field or Source? I forgot that was the original question, lol . . .
"value" is valid, but it's really vague. I like "source" or "template"
I guess "template" creates a bit of a silly name
PoolableObjectTemplate.Template
You absoluely can, as long as the abstract class inherits from a Unity object type!
But if these are not Unity objects, it gets a bit more complex
you can still absolutely store an array or list of an abstract class
It just won't be serialized correctly by Unity -- it will only remember the members from the base class
Hi all! I'm new to coding in Unity and keep running into a NRE error "Object reference not set to an instance of an object" whenever I try to reference a function from another script. I have the script I'm trying to reference (ScriptB) called in the script I'm working in (ScriptA), and initialized in void Start(). I have looked at a bunch of examples and I'm just not sure what I'm doing wrong. Any help would be super appreciated!
You can use the [SerializeReference] attribute to change how it stores these non-Unity objects. Unfortunately, Unity doesn't provide an inspector UI for a field stored that way
Something on that line is null, but you're trying to do something to it anyway
What line has the error
(but there are third-party packages to provide the interface)
You can read about how [SerializeReference] works here
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/SerializeReference.html
This would be the second use-case -- "You want to use polymorphism..."
void Start() {
scriptB = GameObject.FindObjectOfType(typeof(ScriptB)) as ScriptB;
scriptB.Function();```
The error happens on the line the function is called
I'm just responding to this last remark here
But it is my understanding that you cannot have an array of an abstract class type.
Then scriptB is null
Meaning the find failed
You probably shouldn't use find at all, drag in the reference if you can
Is "dragging" the reference when it's literally dragged in Unity into the little slot that is created for it under the script? Sorry I have no idea what the terminology is! I do have it dragged into that little slot though. I'll delete the find
Yes, it's literally dragging the object you want into the box. If the Find fails, you'll be setting the variable to null
All of the find methods return null if they can't find the correct thing
You should use something like FindObjectOfType if and only if you cannot reasonably assign the reference in the inspector.
Notably, it doesn't find things that are disabled
are you thinking of GameObject.Find?
The docs do say...
Returns the first active loaded object of Type type.
but Object on its own doesn't have the notion of being "active"
Perhaps it behaves differently for anything inheriting from Behaviour (and Collider, and Light...?)
Ah, right, this is a FindObjectOfType, not a pure Find
now i'm wondering what that means
Thank y'all for that info!!
It's giving the NRE still, is there a specific way that the scripts have to be organized in order to find each other? If one script is inside of another folder in the script folder, is there a way that needs to be specifically referenced in order to find it?
No, if you've dragged it in, and you aren't overwriting the variable, chances are you have another instance of this script where it's not set
You can click once on the log entry to be taken to the object that caused the error
those properties in point 2 can be applied to every item so basicly you would have one Item class which would implement interfaces for functionality and use scriptable objects to store data of given item, also it can store functionalities, but interfaces cant be serialized, so some worka arounds would be required
Is it even affected by Behaviour.enabled and such, or is it just the affected by the active state of its gameobject?
I don't remember tbh
this is finding literally any unity object, including things that are not components
well, it does have some limits, because it can't find things that Resources.FindObjectsOfTypeAll can find
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Resources.FindObjectsOfTypeAll.html
you can crash the editor by randomly destroying objects you get from this
very funny
I know, just wondering if Behaviours with enabled = false count as "inactive"
I would split the lootable class. One class for the item when it's in your inventory (InventoryItem) and one where it's on the ground (LootItem). The LootItem class can have a inherit from interactable, and have parameter for InventoryItem so that it gives it to the player upon interaction.
Why would you though ?
It’s best to separate them
It’s easier to maintain and expand on if they’re separated
It’s a good way to handle what you want though for sure
Modularity is important for the system you want
Well… Loot item would likely be a game object in the scene, possibly a monobehavoir. An item while in the inventory would be handled by the inventory script. It’s redundant to do both, and will only make it harder to maintain.
Is there any way to have a script copy a mesh and create a terrain from the mesh in game? Like if the mesh is changing while in game, the terrain mirrors it
If you need stuff like model data held in the inventory item, you can simply encapsulate it and have LootableItem read it
No. I’d just be one way.
LootableItem would reference from Inventory item.
I want to make a combat system but I dont have ANY idea of how to do it except for the input. I've attempted to do it but everything was glitching even without console errors so I just deleted it all and I need something or somewhere to give the first steps to this HELL of system (it's 2D btw)
You need to design and consider what kind of combat you even want. there are tons of tutorials out there, but you'll likely need to add your own logic to customize it for your use case.
part of your message makes it seem like you just need to work on debugging more. "everything was glitching" is not helpful to you at all. You should have a good idea of whats actually going wrong, then for example find out what value is wrong, and why it is wrong
so my script has to be in the component I want it to trigger it can be under camera for example and check if the player touched a collider gameobject
First, I would get an attack to work. After that, I would start chaining from one attack. This step can be done in a few ways. Do you have an attack window (time) to press a button again to chain your combo? As long as it's pressed before the current attack ends, it will chain . . .
Pass a reference to the player in the interact function
Do’d likely need it for other things, like playing an animation when opening doors
hey guys question how do you make an invisible 2d platform? im trying to use my regular platform but changing the Z makes it not interactable
Why do you need to change the z axis?
because i want like a platform ___ to turn like this
\
i just want a frickin punch to be done when you click. Nothing more than that
thats the point, there's nothing showing up in the console or something. It just refuses to work, and idk whats going on
can i get help with my code ?
https://paste.ofcode.org/Nth7XLdUhiY3EhLENEHn8t
im trying to spawn gameobject but it spawn more then 1 time
Well, it is inside a for loop
so if that condition is true multiple times, it'll make more than one
the button is 3d mesh so i use the triggered stay to get get the click virtualmouse to work
No I mean it's literally inside a for loop
I'm assuming getClicked is only called once so the stay is fine
is there better way to use collision to make it lop ones and let me hover it like the triggeredstay() ?
but you're starting a coroutine that contains a loop
nothing showing up means you weren't debugging properly. if nothing showed and there was a Debug.Log first in your method, that means the code wasnt running. "It just refuses to work" is not a thing. It works exactly as you wrote it to
again not much can be said, especially not without specific examples as to whats not working
yea i thouth maybe the say fuction happend too fast so i tried to slow it down
i want it in a loop but not spawning objects if the boxindex[i] = -1
i only have 1 object that is in 1 eveything else is -1
There's a lot of conditions there, try logging values to see if the numbers are what you expect
and why the heck the code would just not run? It was a component from the object I wanted, and everything was apparently ok
Did you ever call the code
Prefab = availablePrefabs[1];
Instantiate(Prefab, Vector3.zero, Quaternion.identity);
If the code didn't run, then something is wrong or not as expected. you have to break the code down and test each part until you find where the problem lies . . .
im just getting onto comms but not seeing the code im guessing that the gameobject might have been disabled.. (a parent gameobject maybe).. maybe the script itself was disabled.. or the function from the script just isn't getting called..
nextly "Log" the thing thats supposedly calling this method and see if it's functions.. (just work backwards)
Put in some logs and see if the value is what you expect it to be when you expect it to be that
thats for you to debug. if you truly deleted it all then i dont really know what kind of answers you expect here. best thing is to just try again and then ask if you have an actual example. all this theory talk will be guess work and might not even relate to your code
by default the object is disabled, but I put it to be activated (and this part works)
If it's that simple, you should be able to follow a simple attack or combat tutorial . . .
actually I've just luckilly found the scripts rn
https://paste.mod.gg/xugjajnrvduh/0 - the input, the only code that works
A tool for sharing your source code with the world!
Okay, what about the code that doesn't work
https://paste.mod.gg/qzpuvjyzawio/0 - the manager. It's supposed to manage the data from the enemies so I can use it easier when adding new enemies in the map
A tool for sharing your source code with the world!
https://paste.mod.gg/skaefiourbsl/0 - the hitbox script, to give damage and stuff
A tool for sharing your source code with the world!
https://prnt.sc/aPmEncnfqoDP img
https://paste.ofcode.org/qsvQ3Hk248SXAhMdGLfsZn code
this is what i get its cuz of the allways checking collition
but i dont know any other way
You can't have more than one MonoBehaviour in the same script file
Are you only clicking once?
yes