#💻┃code-beginner
1 messages · Page 657 of 1
anyone know how to give rigidbody a definition for addforce
Might need to rephrase that question to make it clear.
i have an error in my code for unity for a sliding mechanic called cs1061, it quotes "Rigidbody does not contain a definition for AddForce and no extension method Addforce" idk what to do not matter how much i change it, this is the code rb.Addforce(Vector3.down * 5f, ForceMode.Impulse);
You'll need to share the code that throws the error.
!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.
Ah, okay. there's no Addforce method indeed
Check the docs for the correct spelling:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.AddForce.html
Also, make sure your !ide is configured correctly(it would show you autocomplete options with the correct spelling).
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
alr thx
I know things deriving from UnityEngine.Object must exist inside a .cs file that matches it's class name, but its that required for things like interfaces and poco classes? (assuming i do want them serialized and shown in inspector)
matching name is no longer required
Only for unity's object types yeah. Although in newer versions, that isn't a thing anymore
i dont think that is even a requirement for unity objects on newer versions of unity. for pocos you dont need to match the name, you can even serialize it when its a class inside a class. Interfaces arent serialized
hello nomnom oh neat, when was that? I assume for unityobjects you still can't have multiple definitions in a single file? or is that cool now too
sad, fair enough tho
imo object definition per file is neater
It is but I am doing absolutely cursed stuff that involves a couple files that contain exactly 1 line of code 😭
public interface IValuable<O> : IModule<O,IValuable<O>,ValueModule,ValueData> where O : class, IValuable<O> { }
just unreadable nonsense
I often put many definitions in a file as I can't stand file hopping 
yup, today i put this together for testing and manually defining all of these + in separate files hurt
public interface IContentBehaviour<B,S> where B : MonoBehaviour, IContentBehaviour<B,S> where S : ScriptableObject, IScriptableContent<S,B> { }
public abstract class ContentBehaviour : MonoBehaviour { }
public abstract class ContentBehaviour<B,S> : ContentBehaviour, IContentBehaviour<B,S> where B : ContentBehaviour<B,S>, IContentBehaviour<B,S> where S : ScriptableContent<S,B>, IScriptableContent<S,B> { }
public interface IScriptableContent<S,B> where S : ScriptableObject, IScriptableContent<S,B> where B : MonoBehaviour, IContentBehaviour<B,S> { }
public abstract class ScriptableContent : ScriptableObject { }
public abstract class ScriptableContent<S,B> : ScriptableContent, IScriptableContent<S,B> where S : ScriptableContent<S,B>, IScriptableContent<S,B> where B : ContentBehaviour<B,S>, IContentBehaviour<B,S> { }
public interface IModuleBehaviour<M,D> where M : MonoBehaviour, IModuleBehaviour<M,D> where D : class, IModuleData<D,M> { }
public abstract class ContentModule : MonoBehaviour { }
public abstract class ContentModule<M,D> : ContentModule, IModuleBehaviour<M,D> where M : ContentModule<M,D>, IModuleBehaviour<M,D> where D : ModuleData<D,M>, IModuleData<D,M> { }
public interface IModuleData<D,M> where D : class, IModuleData<D,M> where M : MonoBehaviour, IModuleBehaviour<M,D> { }
public class ModuleData<D,M> where D : ModuleData<D,M>, IModuleData<D,M> where M : ContentModule<M,D>, IModuleBehaviour<M,D> { }
public interface IModule<O,T,M,D> where M : MonoBehaviour, IModuleBehaviour<M,D> where D : class, IModuleData<D,M> where T : IModule<O,T,M,D> where O : class, T { }
public class ValueData : ModuleData<ValueData, ValueModule>, IModuleData<ValueData,ValueModule> { }
public class ScriptableItem : ScriptableContent<ScriptableItem,ItemBehaviour>, IValuable<ScriptableItem> { }
public class ItemBehaviour : ContentBehaviour<ItemBehaviour,ScriptableItem>, IValuable<ItemBehaviour> { }
100% cursed
id question what you really need this for but I dont think id really want to know. There are likely ways you couldve avoided this but 🤷♂️
unnecessarily complex code isnt a good thing
Oh it's absolutely likely avoidable, most of this is just a learning exercise than anything directly practical
the general gist of the intents is building a foundation for composition based content creation with a sibling-esque relationship between the behaviors and the data, as well as in a way that lets me define a lot of it in a re-usable package. A lot of this is extra ugly in an attempt to make the actual usage of it look a little cleaner even if that's not strictly ideal
Am I crazy? How do I set the image of an image component on the UI? Isn't like that?
the image component is an image
I am extremely confused by the difference between a UI Image and an UIElements Image
UIE Image
sorry i realise now thats a confusing question
you have two skillIcon's there
what is both
Both are the same tbh
I just wanted to change the image of the first one to match the second one
skillIcon.sprite = skillReferenced.skillIcon.sprite ?
It's like pretty confusing calling the image of an image sprite, being that sprite is another way of rendering stuff that is different from the image component, tbh
I agree to an extent
but I think your issue is in the other direction
I would probably make more sense if Image was called ImageRenderer
Makes sense, yeah
Also, what the heck is the difference between the UIElements one and the UI one?
Are they the same?
These are different ui systems in unity. UI one is using canvases. UIElements is close to html and css.
And image component makes actually makes sense as it contains the image data/settings on the canvas. It doesn't render it itself as opposed to SpriteRenderer. The canvas renderer is responsible for rendering all the canvas elements that can be rendered.
Sprite is section of a texture, it describes what part of a texture is used during rendering.
Then, the editor should not call that source image then
Cause it's a sprite?
I dunno, just feels confusing
what in your opinion makes an image not a sprite and a sprite not an image
I guess so. The naming can get confusing.
I am just confused by how we have a sprite renderer component that requires a sprite called sprite and a Image component (not renderer), and requires a sprite but calls it "source image"
And extra show when referencing an Image pops u 3 different types of Image
But sure, it's fine
I got it
ye, imo Image and Sprite are pretty interchangeable words that in practice usually refer to the type of content in them and the target size
my issue with that as you said is that SpriteRenderer clearly refers to rendering a Sprite but Image in my head refers to the asset and not the component in charge of renderering them
Image component -> Image Renderer & Source Image -> Sprite
I wouldn't mind it being called source image if the component was called ImageRenderer
Probably different people working on these components at different times and were not explicitly aware of the naming in the other scenario.
Oh, and a thing I am doing that I am not sure, matters much. If I have singleton instance to reference stuff, should I make a parameter for it and store it on the script if I am gonna reference to the Instance over and over? It's faster or doesn't matter much?
What kind of parameter?
Like doing this rather than referencing the Instance each time I am gonna do something with the selectedEntity
I am assuming it's kinda the same, but not sure
I'm still not sure what you mean by that. Referencing what exactly each time?
What's the other way you were planning to do this?
I am basically making a "selectedEntity" variable on the script to store it within itself and referencing that instead of the "EntitySelectSystem.Instance.selectedEntity"
Ah, okay. There should be virtually no difference in terms of performance. So it's more of a readablility thing.
Yeah sometimes i do static getters to point towards stuff to reduce the writing eg.
public class MyImportantReference : MonoBehaviour { }
public class MySingleton : MonoBehaviour
{
public static MySingleton Instance;
private MyImportantReference reference;
public static MyImportantReference Reference => Instance.reference;
}
That seems kinda hard to read for my level still tho
is it the =>?
Is the referencing something to another something on the very declaration of that something, so yeah, kinda
I still get confused by list not doing snapshot values when getting referenced
if it helps this is functionally the same thing
public class MyImportantReference : MonoBehaviour { }
public class MySingleton : MonoBehaviour
{
public static MySingleton Instance;
private MyImportantReference reference;
public static MyImportantReference GetImportantReference()
{
return (Instance.reference);
}
}
no stress tho
Does it need to be static tho?
doesnt need to be, but means you can do MySingleton.Reference rather than MySingleton.Instance.Reference
which seems minor but depending on the name and usage can add up in cleanness
It would mean that the reference cannot be changed to anything else if I am not mistaken right?
But since it's pointing to another variable that can be changed it's no issue
It's that the whole point?
yeah the Reference is what c# called a property just using the get part of it. it's basicially a function disguised a variable
it is just a "pointer" (i use that word humanly not programmically) to another value for convienence
Cool, I do try to avoid stuff that would make me read it twice whenever possible, so I don't I am think I am using that for now lol
ya i feel that, learn at your own pace but properties are goated
do you understand ref vs value types as a whole?
or do you already understand it but just haven't internalized it?
I understand it, I think
But I am on that ground where I would probably misuse them if I start using them frequently
my midscript has an audiosource assigned to it however when I run the game and the game creates pipeobjects the midscript just dosent have an audiosource assigned to it. there is also a screenshot of the pipe prefab.
here is my midscript : https://scriptbin.xyz/ocecuvadam.cpp
Use Scriptbin to share your code with others quickly and easily.
Chris is not talking about the ref keyword, but about reference types and value types.
Yes, I understand it
Share the actual prefab screenshot.
if it's the latter, it'll probably just get better with time/experience/practice, unfortunately. i don't think there's really any shortcut to internalizing a system like this
If you do then I'm not sure what " if I start using them frequently" means, because you probably DO use them freequently.
where's the audiosource? in the prefab?
I do, but I also use a lot of others things I do not understand by just using the interfaces and scratching the surface lol
isnt the pipe prefab the screenshot you mean? or do you mean of every component in the prefab?
uhm.. I think I see the problem now
Oh, it is. But I want to see the Mid object on the prefab
Yeah, this
LIke, I have no freaking idea on how to code a shader, but I can get some nodes working. I have no freaking clue on how a List works internally, but I yet spam them like crazy lol
a list is just an array that gets replaced if it's too small
It's sometimes a good idea to try and investigate things a bit deeper. Can open up new perspective and understanding of things.
do you know how references, the stack, the heap work? if you understand those it might help
ok sorry I was lost I forgot to add the audiosource to the prefab
it works now

No, and my rule of thumb is not trying to learn something I cannot apply inmediatly to something usefull, cause I am gonna take double the time to learn it and I am just going to forget it later lol
I am the type of learner that when sees something doing the something I need, everything clicks inmediatly, otherwise it's just noise.
that.. sounds like it'd stunt your progress
understanding how reference types and the stack work would be applicable to the entirety of programming
what if you never "need" it
Then it wasn't that necesary to begin with
Look, I don't even use keybind shorcuts on anything, just cause I find clicking on the thing easier to undertand
And I play freaking Starcraft lmao
I mean it's going to help you a lot to be at least aware of these things
Source Image is just the field name for description. The expected type is that of a Sprite.
forsure but modern programming languages have a ton of features that are massively helpful in productivity and readability that aren't neccasarily "neccasary"
That's why I ask a lot of if I am doing stuff right, cause I don't really have much to compare to
which is why you'd generally learn about what you can do, not what you have to do
Hmm, you aren't referencing an instance every time however you are accessing a static field that has a reference to your single instance where you're attempting to access the member (refresh rate) of that single instance.
Bypassing the instance field/property wouldn't save much time. If you'd prefer not having to access the instance property every time.. you could reference the instance in that particular scope or class and refer to that variable instead. Example:cs private EntitySelectSystem system; private void Start() => system = EntitySelectSystem.Instance;``````cs if (system.selectedEntity == null) ...
Probably better to just make a property that points to EntitySelectSystem.Instance as this will avoid possible race conditions if more things rely on eachother in Start
Ideally this is all set up beforehand but it's a tricky topic.
Hi, how i can select 1 random number in a list of numbers. For example, i want to select a number in this list [1, 8 ,98, 72, 64, 670, 4980]
just get index between 0 and element length of list and get value with list[index]
List<int> list = new List<int>() { 1, 9, 98, 72, 64, 670, 4980 };
int index = UnityEngine.Random.Range(0, list.Count);
int element = list[index];
i think you mean this
or shorter version:
List<int> list = new List<int>() { 1, 9, 98, 72, 64, 670, 4980 };
int element = list[UnityEngine.Random.Range(0, list.Count)];
I have debug logs for each rotation that happens
but those didnt really help yet
do you have any suggestions?
Can you share a video of the issue properly? mp4 and drag and drop it in the discord.
Sure
The player model often overrotates and I cant seem to properly sync the rotation (of the player model) caused by the movement script trying to align the model with the terrain and the rotation caused by the script that aligns the player model with the camera rotation (so it works like a 3rd person shooters camera)
This is not mp4. I would have to download the file to see it.
Sorry, accident
Ok, so do you know what line of code causes the rotation?
Do you see any of the logs related to rotation when the issue happens?
I would have say its the script trying to align the model to the ground, but I don't actually get the debug logs for those rotations
I put debug logs into the gravity application process, which applies gravity of the model is not on the ground (based on 4 raycasting points)
and the weird rotation is caused by the gravity
Hey guys Im trying to replicate the IK Stretch from Blender but failing, probably doing it wrong but I dont know what the correct way is too bad at math. Im using the unity animation package for the IK part and this is my stretch script. Any help is much apreciated!!
'''using UnityEngine;
public class StretchyIKBone : MonoBehaviour
{
public Transform start; // Root of the chain
public Transform end; // Tip of the chain
public float stretchiness = 1f; // 1 = default stretch, higher = looser
public Transform[] bonesInChain;
private float originalChainLength;
private float[] originalBoneLengths;
void Start()
{
if (start == null || end == null || bonesInChain == null || bonesInChain.Length == 0)
return;
originalBoneLengths = new float[bonesInChain.Length];
originalChainLength = 0f;
// Calculate total original chain length by summing bone segment lengths
for (int i = 0; i < bonesInChain.Length; i++)
{
Transform bone = bonesInChain[i];
Transform child = (i < bonesInChain.Length - 1) ? bonesInChain[i + 1] : end;
float length = Vector3.Distance(bone.position, child.position);
originalBoneLengths[i] = length;
originalChainLength += length;
}
}
void LateUpdate()
{
if (start == null || end == null || bonesInChain == null || bonesInChain.Length == 0)
return;
float currentDistance = Vector3.Distance(start.position, end.position);
float stretchRatio = (currentDistance / originalChainLength) * stretchiness;
for (int i = 0; i < bonesInChain.Length; i++)
{
Transform bone = bonesInChain[i];
Vector3 scale = bone.localScale;
scale.z = stretchRatio;
bone.localScale = scale;
}
}
}'''
Heres how it looks currently: https://streamable.com/yo697j
- Actually open your console and monitor the messages.
- Make sure the console is not set to fold the messatges.
- Remove unnecessary messages.
- Make tour logs more informative. At the moment you are using the same message in different places.
Hey guys! I’m very rusty with unity right now and I really need some help making collectibles for my 2D game. It’s supposed to be somewhat of an endless runner where the collectibles move left along with the background to simulate movement. I’ve made prefabs of both the background and the collectibles and put the moveleft script on both of them. I also have spawner gameobjects that have scripts that are supposed to spawn them at different intervals. the collectible spawner is the one on the right. the weird part is that the background spawner/moveleft works perfectly and successfully loops the background without issue. the collectibles spawn, but they spawn in the same area and don’t move left despite having the script attached. does anyone know what the problem might be? any help is very much appreciated :D
!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.
!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.
crap mb
Sorry.. will remember that now
Alright, I've made these changes, and it seems like the gravity is being applied and the players "Rotating Back" debug message is recived
Here is my current code: https://pastebin.com/Dp2gPmAG
Maybe you can see the logic flawn I can't
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.
yes, it is, but if now i want to select only 3 numbers of the list, for example 1, 9,98, how i can do yhis?
That log would only print if the ray pointing directly below the object doesn't hit anything.
if (!Physics.Raycast(
groundCheckFront.transform.position,
-transform.up,
checkDist,
groundLayer
))
{
float rotSpeed = (90f * Time.deltaTime);
transform.Rotate(rotSpeed, 0f, 0f, Space.Self);
Debug.Log("Rotating back to the ground ");
}
You should draw some debug rays showing where and how far the ray is cast
make it loop with for
sorry, i say it bad, how i can select a random number only in 3 numbers of the list
for example in the list i want to select a random muber beetwen 1 , 9 and 98
Alright, I'll get to it, I'll get back to you if I have something
create new list with that 3 numbers and call Random.Range(list.Min(), list.Max())
ok
alright so the score updates by 1 good, but then it stays 1 when i pass more trigger blocks, whats the issue
oh wait
!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.
'''cs
using UnityEngine;
public class TriggerScore : MonoBehaviour
{
int scoreNumber = 0;
void OnTriggerEnter(Collider other)
{
scoreNumber++;
Debug.Log("oh no you triggered me " + scoreNumber);
}
}
are you aware that this score number int is per instance
but int is for whole numbers and float is for decimals no?
You miss understand. Do you want many of these triggers to all contribute to 1 store value? Atm its per instance
no no like update the variable by 1 every time i pass them
Yea its doing that currently
but if you have many TriggerScore instances in your scene they all have their own score that they increase by themselves
oh wait what?
i think i got it let me try something
like what you said
yeah still doesnt work
what did you try
so like
i have these 3 blocks i have to pass, all with the same trigger as the middle one and the same script
what did you actually try to do to solve this when you said "let me try something"
and it prints this
ohhhhh, i deleted the script from 2 of the triggers
have you considered instead putting the component on whatever is going through the triggers instead? since your score variable is not static a separate version of that variable exists for each instance of the component. so if you instead put the component on the object passing through the triggers then it will only exist on that object and there will be one score variable getting updated instead of multiple separate ones
OHHHH
alternatively, you could make score static so each instances shares that same variable, however that may not be ideal, especially if you don't understand what static is
THATS WHAT I MISSED
let me try putting it only on the object
bruh i was so stupid how i forgot thats how it works lmao
thank you all for helping
I was trying to question this but guess that didnt get across 😦
yeah im still very new but explain please
explain what, exactly
instance variables vs static
how to share a variable between scripts
many scripts modify a varible in 1 instance elsewhere (e.g. game manager)
OR use static variable
that's not quite what is actually happening with static though, it's just a simplification so you would understand what i was talking about, it doesn't "share a variable between scripts" it makes the variable not associated with a specific instance of the object.
also you need to understand the difference between "scripts" (which are just files that contain code and mean nothing within the running application) and "objects" which are instances created from classes and structs defined within the code.
ok thanks
is unity muse ai worth it
ok but how do i make my object move forward in a direction but if it collides with another one of my game object , i want it to explode
split that into separate tasks
make it move, specify a direction, detect collision, make it explode
ok but how? i use visual scripting
ask that in the visual scripting server
you'd probably want an rb for the collision check, then you could use that same rb for the movement
where is it
How to write this code in a non deprecated way. Tried but couldn't find any relevant information for an hour and unity has not updated thier docs despite it being a year now ```public void MuteSounds()
{
allSources.Clear();
AudioSource[] sources = FindObjectsOfType<AudioSource>();
foreach (AudioSource source in sources)
{
allSources.Add(source);
}
foreach (AudioSource A in allSources)
{
if (ContinuosSounds.Contains(A))
{
allSources.Remove(A);
}
}
foreach (AudioSource A in allSources)
{
A.Stop();
}
foreach(AudioSource A in ContinuosSounds)
{
A.mute = true;
}
}```
Find objects is the deprecated part
if it's telling you that it's deprecated, then i'm pretty sure it also gives you the alternative in the subtext, if you hover over the warning in the IDE
the alt throws an error. AS it always does with the intellisense
what's the error given?
FindObjectsByType gives you an error?
also about docs- FindObjectsByType is listed in the docs page for FindObjectsOfType
it returns an object not an audio source and to try and get the audio source version causes even more errors
you can try to write it yourself. Its asinine to deal with
show what you wrote
ok, are you gonna say what the errors are
i just said the error
you have not
it returns an object and u cant get the audio source from the object
you have said the issue, not the error message
also, like nav said; show what you wrote
i deleted what i wrote
undo
This conversation is straying form the original point. Who knows how to write the above code in a non deprecated way?
they literally told you how and you said its grabbing the wrong thing, so show what the new thing is.. its common sense
buddy we can't fix an issue if you refuse to tell us what the exact issue is and what's causing it
you've apparently followed the steps to get the new version already; that didn't work. so now tell us how it isn't working
so the triangle is pointing to the gold thingy and i want the pointer on top right to be the same rotation as the triangle but when i rotate (player), the pointer also rotates. i'd also like to mention pointer is in canvas
code for pointer:
void Update()
{
transform.rotation = pointer.transform.rotation;
}
in this case "pointer" is the triangle
and what is transform.rotation supposed to be
rotation of the pointer
huh and what is pointer supposed to be ?
the gold thing on top right
You can, easily
is the white triangle child of the player ?
yea
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Object.FindObjectsByType.html
Exactly what the IDE says to use
hmm not 100% sure but that could be affecting the rotation
i want the pointer to be the same rotation as the traingle
could it be bc canva isn't rotating with player
it was the issue
thanks for help @rich adder
ohh how did you fix it?
i added a script to the canva to rotate with player
bc ui normally stays in place and it caused the issue
If it makes sense
huh..thats weird...canvas doesn't rotate afaik
I think normally yes but i can change it with script
oh ok cause when i tested it RQ I was able to get UI to rotate fine , I'm guessing you might have referenced the wrong object?
Vector3 mousePosWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePosWorld.z = 0;
var dir = (mousePosWorld - thing.position).normalized;
thing.up = dir;
uiThing.rotation = thing.rotation;```
you might want to have that rotation sync in LateUpdate to make sure it gets the rotation of the current frame rather than the previous frame
or just set it in the same script, like nav's example
hello everyone! Could someone help me with a little project im working on for school?
!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
and don't ask to ask
Got it, so be more specific then?
I mean it worked perfectly until i turned right or any direction
I'm trying to do a road controller where once the player crosses a section of the road, another one spawns in front of it.
But now it works so i'll leave it alone thanks for help
I'll try to describe what my code is suposed to do:
The player spawns on top of a road which becomes "curr-road". Once the player exits that road, it becomes "prev-road" and the road that it entered becomes "curr-road" and another one infront of it spawns called "next-road" But unfortunately its a buggy mess, roads spawn on top of each other among other things.
A car, which is the player, has a box collider on its rear which is suposed to only trigger when it touches a roads box colider as well, not the whole road.
I dont know why, but i think the box collider on its rear touches a road and triggers, not just the roads own box colider
showing the code would help.
and perhaps a video of what's happening
use mp4 so it gets embedded in discord
!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.
not screenshots please
It's also completely unclear which object this script is on, or even which script this is
The code i showed is the "Road_Controller" script
im gonna send it properly now
A tool for sharing your source code with the world!
So which object is this script attached to?
it is attached to "Free Racing Car" which would be the player, ill rename it actually
I mean one thiong you should really do is observe the car's position etc. It seems like maybe it's going flying? Probably because it's colliding with teh newly spawned road in a degenerate way.
It is driving on the ground, but something in the code is being messy. I think its because of the colliders
but its weird because the only things i have as "Is Trigger" are the box collider on the car's rear and the box colider on end of the road.
Wait how do you even have a non-convex mesh collider on the car?
Is there a third collider there too?
the "body" of the car has a colider of its own, the collider i want to use is on the prefab itself, maybe i should just use the collider on the body?
Two things of concern:
- Non-convex mesh colliders cannot be used with dynamic Rigidbodies (that's probably one of these errors/warnings)
- Your non-trigger colliders are ALSO going to trigger OnTriggerEnter with the road. So that's going to run at least twice. Only one of the colliders needs to be a trigger for that.
yes you need to delete that extra collider
and you can't use the non-convex mesh collider at all for a moving object
it needs to be convex
or you need to replace it with a bunch of smaller primitive or convex colliders
ok so now i only have one colider on the whole thing which is a box colider on the body of the car:
And it is triggering events because roads still spawn although still weirdly
So now you need to get to the bottom of that "weirdness"
I highly recommend dragging your scene view to be also visible
so you can watch the scene from scene view while it's running in game view
then you can see exactly where the roads are spawning etc.
and where the car goes
i dont quite get that, but i made the main camera see more of whats going on
like this
make it so you can see the two side by side
then you can watch both
Just drag them by these tabs so they're side by side
Got it! But i think it works now? It ran for a while without problems, ill give it another try
It does work! But now i'll try making it so it spawns 2 roads so the player can see whats gonna be happening better.
I know for a fact that this is going to be something stupid that I'm missing because I'm sleep deprived, but I want to set a fadeToNextScene boolean inside of my BlackFade script to true after the player finishes talking to an NPC
I've set it so that I have public BlackFade blackFade; at the beginning of my DialogueController, and once the player finishes talking I wrote blackFade.fadeToNextScene = true;
But it's just coming up as a null reference, I know for a fact it's probably something really dumb that I'm missing but I can't think of what it is 
Well did you actually assign the reference?
then blackFade is null
Just writing public BlackFade blackFade; creates a reference variable. You have to acutually assign that reference to something for it to be usable
either in code with the = operator, or in the inspector
First image, is the code for the player, if the collide with the object that has a tag called "PickUp" it will make the object dissappear. Second image, is the code of the AI (enemy) that follows the player, I tried to make it so when the enemy also touches the same object (first) it will make the object dissappear. (This is for fun purposes only), I'm not getting any errors however the code doesn't seem to work either. Does anyone have an idea why?
Quick question, why do you have "&&"? I mean why would you need an AND when you already have the player colliding/touching the "road"?
start by debugging it
😭
I mean how else you want to solve a problem without debug ? we all do it
You have to compare the actual result vs expected result
😭 (how to do that) 😭
well start by testing each part of the code is doing / hitting how you expect it to. Bigger problems must be broken down into smaller to test problems
process of elimination, 1 by 1
You have lots of conditionals you have to test
also this code screams AI generated...
hello
I am actually trying to learn something
😭
I just copy and paste the sample
Oh okay good.. at least thats one lest problem then
so I can come back and understand what's happening
well did you learn what each part is doing then you can kinda use that to test each part
kinda
you can start with Logs, put them inside the if conditional statements and see where its printing and where it isn;t
But isn't this already pretty straight forward?
{
if (other.gameObject.CompareTag ("PickUp"))
{
// Deactivate the collided object (making it disappear).
other.gameObject.SetActive(false);
}
}```
all I can do is change what's inside the if
no?
or print whatever the object is colliding into
well there is nothing wrong in the code itself per se... but how do you know that function is actually running ? did you verify that
okkkkk
👍
makes sense
the steps of the debug is to eliminate any doubts / assumptions with hard proof
so kinda like this?
{
Console.WriteLine("It's working");
}```
and has to print something here?
Debug.Log("It's working");
- Console.WriteLine doesnt work in unity
ok
- You should probably keep the code as was, but you can put Log statement BEFORE if statement and actually print what you hit too, with its tag as well
i honestly use print more than debug.log lol
Debug.Log("It's working and we hit: " + other.gameObject.tag);
eg Debug.Log($"{other.name} has entered the trigger with tag of {other.gameobject.tag}");
void OnTriggerEnter(Collider other)
{
// A
if (other.gameObject.CompareTag ("PickUp"))
{
// B
// you technically can't be certain this is failing or suceeding.. without a log at (A)
}
}```
like this?
sure the more details you print the better
rarely you need "RandomText" type of debugs, better to print values
theres also string interpolation..
Debug.Log($"Like this we can log the name of {gameObject.name} without any extra plus signs and quotes.");
string interpolation
Is that how you call it?
Debug.Log($"It's working and we hit: {other.gameObject.tag}";```
debug.log beast mode
void OnTriggerEnter(Collider other)
{
Debug.Log($"{other.name}It's working and we hit: {other.gameObject.tag}");
}```
Nothing is being printed
it doesn't work
there you go you answered yourself
many reasons it could
https://unity.huh.how/physics-messages @open apex you can go through these steps to guide through reason it could fail
if(bool){
Debug.Log("The bool is true");}
else{
Debug.Log("The bool is false");}```
there was a time..
I think I understand what the problem is now
nice
The yellow things are objects that give you a point
When the player touches them it cannot go through it
But the enemy can
did you mark them as Trigger?
yuuup, well if they're triggers the player could
and the OnTriggerEnter() function would be called
yes
this function works totally for the player
not the enemy
When the player touches them it cannot go through it what do u mean by this then?
the enemy most likely does not have a rigidbody
they collide
is that desired?
it sounds solid then..
then the object is set to false
can you show the inspectors so we know for sure
(cubes, enemy and player)
usually collectables dont make the player collide with them
that'd ruin my flow-state
Hello, I'm trying to make a basic flappy bird game without following a tutorial. Are the following things a "bad" implementation?
I make a boxcollider at the bottom of the screen that when my bird collides with it, I lose (fell off the screen), and the box collider's transform is updated with my player's coordinates so it follows me on the x axis. I want to try "object pooling", but I'm unsure of what that entails. Do I flat out disable the pipes that leave my screen? Or do I just disable their sprite renderer until they're needed again?
sounds like you should not be worrying about pooling yet
thats extra complication for a beginner
for flappy bird ur basically just positioning them on the opposite side of the screen once they go out of view
oh
object pooling is basically just reusing the pipes. Disabling them when the go out the left side of the screen, enabling and repositioning them when they reappear.
Also most flappy birds don't move the player on the x axis, they move the pipes.
😭 oh my god
most infinite games try to move the objects towards player instead of other way around, to avoid dealing with Resett of World Pos to avoid Float overflow
You get weird glitchy shit happening at really high float numbers in world
yeah the bird stays in place
you create the effect of "movement"
😭
treadmill
games are all about smoke and mirrors
ti siento yowler
carrot on a stick
I'm laughing so hard
lmao
same shit happens to me
I do something for hours
realising that, that was not meant to be done that way
Secrets are My Life!.
yeah so the enemy does not have a rigidbody
yeahhhhhhhhh
and the one on the cubes are kinematic, which would require at least 1 dynamic to trigger a trigger 😵💫
I kinda realised that now
dont put physics components on pick up items, its a waste of resources
ill usually put RB on player/enemy and triggers for everything else
and my trigger code on the trigger asking about the rigidbody.. not the other way around..
so what have they done in the tutorial?
I'm kinda confused rn
I tried to put an rb in the enemy object
are u following it u should know
lol
Spawn camp
it'd have to be Kinematic as well
I'm bout to cry
so it doesn't conflict w/ ur Navmesh Agent
assuming the enemy is a navmesh agent you can put a rigidbody just to grab physics message but you need to Lock it in place with constraints
I'm trying to understand tbh 😭
lol.. well where are u stuck?
can you link the tutorial?
why not reverse 1 step.. and try again slower
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
The only reason I half understand it's because I kinda used common sense
and some c# studying
and even in the videos
when they explain it
they don't fully explain
weird I get a 404 with these links..
such as: OnTriggerEnter, I don't fully understand it, it's mostly a guessing game
use this
same thing
old link
yea i got it 👍
https://learn.unity.com/course/roll-a-ball/tutorial/adding-ai-navigation?version=2022.3 guessing hes on this step
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
yes
I'm just trying to learn rather than cut corners
I can finish the tutorial
but whatever is stuck in my mind
I just try to eliminate it
What I'm trying to do rn is not a part of the tutorial
dont stress about it..
collisions/triggers and that exact code ur working on right now
appears ALL OVER game dev
you'll get lots and lots of experience with it
in order to do that you have to grasp the few requirements for the specific thing you need to do.. For example a Trigger message needs at least 1 Dynamic rigidbody between the two colliders
Is there some kind of tutorial that actually explains things step by step?
because this is supposed to be a "beginners tutorials"
and doesn't teach things in detail
well usually start with the Pathways
Roll a Ball is kinda old i think
You are looking a video on specific things you probably wont find them,
Just quick question, this is how I think it works, correct if I'm wrong:
"OnTriggerEnter" is some kind of a library and "Collider" is a syntax found in that library, "other" is just what we name is, for ex; "other.name" the name of the object that it has collided into
no OnTriggerEnter is just a method..
so just kinda do more and more programming?
I don't know what it's called
so I called it a library
well its wrong hence the correction
you dont want to start off the gate with the wrong assumptions
👍
is it a good place to start from?
A library would be PhysX , what Unity uses for Physics
I kinda got ChatGpt to draw a road map for me
OnTriggerEnter OnCollisionEnter etc are built in Unity functions/methods
Free tutorials, courses, and guided pathways for mastering real-time 3D development skills to make video games, VR, AR, and more.
like Update() Start() and everything like that
how does it look?
it automatically gets called every physics tick
idk I dismiss anything "AI"
lol. same credibility--
its usually gobbledygook
trademarked
so how did you guys learn to program enemies for your games?
ill let u know once i finish
LMAO
wanted to buy a book which this guy wrote
with time and experience.. also enemies range from very simple to highly complex like GOAP and Utility etc.
mehh imo with the amount of good free resources online there is hardly a need to spend money on this stuff
so asked chatgpt to generate me a roadpath teaching the same things
the most complex enemies you'll see from me are the likes of the Goomba's
from super mario bros
I havent spent a dime , learned it all with whats online
But where am I supposed to start?
start by not thinking too deply about doing Enemy AIs and such
heres a little list i put together @open apex
for example you guys told me roll a ball is not a great example
sebastian lagues playlist really helped me get my feet off the ground
Could someone help me try figuring out what could be going on?
What i'd like to do is: When the car touches the box colider on the end of the first road, it spawns another road infront on the road infront of it and calls it "next_road"
When the player exists the next road, it's suposed to another road infront of the next_road which would be called nextnext_road.
link to the code: https://paste.mod.gg/fvsqnriitenw/0
A tool for sharing your source code with the world!
You're trying to Jump 8 steps forward when you should be taking steps back
example.. before touching Enemy AI you should probably know the differences in Trigger messages how they relate to rigidbodies etc.
I'm trying to understand where to start
and whats the problem? can u be specific
Should I drop this course and start with this rn?
they're short.. its not really a course..
it just introduces u to unity concepts, unity c#, etc
u can stop pause, branch off, discard or w/e
only u can know the best way that u learn
it talks about Triggers 😉
well, first of all, roads often spawn on top of each other (you can see that a barrier spawned on the road that has a sign, thats another road spawaning on top of it) and then you can see that the road the car was in at roughly 1:10 despawned with the car below it.
I meaannn, I have been trying to learn player movement and every tutorial I have seen hasn't taught me jack shit and this has been the only "beginners tutorial/course" that has taught me something
while its good you wanted to stray a bit from the tutorial for something new, you should hold off on that until you learned what was actually in the lesson so you can replicate it on your own without the tutorial, once you have that with time you can slowly diverge more into your own
they are there to show "here is how I did it" instead of "you do this like this because xyz "
the pathways I linked also will show you step by instead of throwing you to the lions right away
hmmm, so after I finish this -> https://www.youtube.com/watch?v=_cCGBMmMOFw&list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw&ab_channel=SebastianLague, how do I know what to do ? I want to do some stuff but all that shows up is "here is how i did it"
Welcome to this introduction to game development. We'll be starting from the beginning, so no prior knowledge of programming or the Unity game engine is required.
Unity can be downloaded here: http://unity3d.com/get-unity
Watch episode 01: https://youtu.be/9iCnjdXEfMA
If you'd like to support these videos, you can make a recurring monthly don...
I want to acutally learn
instead of looking at "how to make player movement " you can do "Ways to move objects in Unity" or something like that
you have to get generic so you get better result
hmm, ok so, go basic and then go more detailed
this way it will explain how each movement does what and pros and cons
always
sometimes my brain just doesn't work
really grateful for your help guys,
I will start working on what you have sent me
for example here is one of the vids I first picked up when learning as beginner
https://youtu.be/tNtOcDryKv4
Check out the Course: https://bit.ly/2S5vG8u
Discover 5 different ways to move your Unity3D gameobjects, see some of the differences between them, and learn which one I usually use.
More Info: https://unity3d.college
I did not care about specific " PlayerMovement " I just wanted to know how to move something and I implement the rest on my own etc.
(keep in mind this vid specifically is old and not best practice , mainly hes moving in Update for a rigidbody when it should be FixedUpdate) but you get the point
In this Unity Tutorial, you'll learn everything you need to know about Moving.
We'll discuss which Unity3D Components to use and how to use them. From controlling simple boxes with Keyboard Input to more advanced character controllers and navigation.
Each section independent so you can choose the part you need to learn about.
00:00 - Intro...
One last question, should I go through everything you guys have sent me and then try do something? OR kind of do both (but mainly the stuff you sent me)?
up to you .. IMO start with the pathways from Unity, when you are comfortable with those then move to the next thing, you are learning for now not making an entire game
So do everything here?
he has a part 2 where he makes a little top down game.. but at that point theres where i branched off and started to want to make my own thing
You dont have to do them all, but at very least Essentials and Junior
then its just looking up piece by piece and then the harder part.. adapting and merging them all together
thats when the experience pays off
part 2 as in 2nd playlist?
a 2nd playlist
thats when you'll combine alot of the stuff he teaches in the previous playlist and puts them to work
but yea its still worth learning how to put all the pieces together even before you have ur own game in mind
ur on ur own there
the genre or platform is often irreverent
its the same building blocks
the input would differ quite a lot tho
not by much. if you properly code the abstraction
i find mobile input fascinating.. i often like to take mobile style inputs and pair em with standalone genre's
u can come up with some pretty unique ux experiences
virtual joysticks for example.. imo havent had their true potential unlocked
this is called " jumping too far ahead"
you're already thinking about mobile inputs? you dont even know how to make something move on screen lol
take the mobile part of out equation for now, just make the thing move.. where inputs come from will be irrelevant
Anyways here is a story for you guys: I kinda develop a few little games before and has always been into game development a bit, so I'm currently studying IT and 4/5 of our lecturers stopped teaching and just started sending us resources and videos of how to do our assignments, most of the stuff that I am able to do it's because I have done a few shit games before and have that little experience 😭 I can't believe they are sending us shit expecting us to fucking know
yea im being a tad sarcastic
development is a bunch of research test repeat
not "do xyz"
in fact most lot of code tests dont have a set solution, its mostly about how you deal
hello! I'm trying to convert a save system tutorial from using binary formatter to Json, but I'm having difficulties loading the data back as a dictionary - it gives me this error
InvalidCastException: Specified cast is not valid.
But I don't know know how to cast it back to the dictionary properly, grateful for any pointers
LMAO
why are you casting it to a dictionary ? you should have a helper class
First thing to do is do GetType() on the returned object and see what it actually is
But typically you should be calling the generic version of DeserializeObject and specifying the type there
Yeah there's an Interface and savers scripts that do all the heavy lifting, this is just to read back from the list of objects with the 'saver' component. saving works fine, just loading back gives me an error
e.g.
Dictionary<string, object> deserialized = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);```
if you don't give it that, it's just going to guess basically
oh I see
(Ok, will start off with pathways and at the same time go through with the playlist. Thanks for the help and have a good night ❤️ )
goodluckk
if (firstroad.active == true)
{
firstroad.SetActive(false);
}
is this a thing?
firstroad is a gameobject
thank you|!
you would need activeSelf or activeInHierarchy
I guess should give context, i want to check if the gameobject is active, would i use this?
Again
one of those two
depending on the specific thing you want
activeSelf is just the checkbox on that object itself.
activeInHierarchy can be false if the object itself is active but its parent is deactivated, for example
Because deactivating an object implicitly makes its children deactivated too
feel free to read the docs for further info
thank you!
this object is just a child, so it wouldn't be a problem using activeSelf right?
It won't be a problem if that's the thing you want to check
if you want to check overall "activeness" then it will be a problem
I'll give it a try, thanks. Also, how do you make your text look like that?
use ` hi code here ` ```
!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.
thank you very much!
I don't even know what to say about this one ngl.
A tool for sharing your source code with the world!
I don't even think i'm checking what roads are active or not.
your logs are showing that your logic is disabling two roads in short order
so there's some bad logic in the code somewhere
Also even when you have two roads ahead of the player active - the logic should only really be activating and deactivating one road at a time. It's just a matter of the distance in front of the player that you would be activating the next road
e.g. instead of starting with one active road, you start with two, and then you're still just activating one at a time, just further ahead
(and still just deactivating one at a time).
So I think your logic is faulty to begin with.
likely
but i really just dont understand what is going on in general
https://paste.mod.gg/wyksusdshnwp/0 heres the whole code if you'd like to take a look.
A tool for sharing your source code with the world!
Basically instead of these named variables you should use a Queue.
When you add a new road, you enqueue it
When you want to delete a road, you dequeue from the queue
it would replace all of those variables
Also instead of having these pre-spawned 10 road objects, you should just use an object pool and a prefab
Unfortunately i don't know how do that and i don't really think i have time to switch the whole system, but thank you for the sugestion.
Do you think i could still make it work as is?
you could it's just a mess
anyway the logic is almost identical to what you had before, you just shouldn't be spawning two roads at once
only at the Start would you spawn two roads
The nice thing about using a Queue etc is the code can handle any number of visible roads at once without changing the code at all
with this one you're going to be manually copying the variables in an ever increasing chain, which the queue and object pool will just handle gracefully.
Im planning on adding a fog so the player can maybe see half of the next road when he's about to leave the current road.
What i could do is start road [0} and a first empty road which once the player passed road 0, would be deactivated and replaced by a proper road.
the first road is just a place holder in a way,
I made a workaround:
I made it so the firstroad positions itself infront of the next_road when the next_road is created that way it makes it seem like next_road was always there.
It is a workaround and doesnt really do what i had in mind, but it works from the players POV and im happy with that.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 2564565f;
void Update()
{
float moveX = Input.GetAxisRaw("Horizontal"); // A/D or Left/Right
float moveY = Input.GetAxisRaw("Vertical"); // W/S or Up/Down
Vector2 move = new Vector2(moveX, moveY);
transform.Translate(move * moveSpeed * Time.deltaTime);
}
}
Why does the movespeed not change at all no matter what I make it?
because you need to set it in the inspector
Also for the future:
!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.
Thanks
hm, can i use physics materials to make moving platforms?
my friend said they did an age ago but dont really remember the details
specifically i want a rotating platform to fling the player in the corresponding radial direction when they jump
I’m not really understanding what { get; set; } does I’m watching a tutorial and they used it like this
{ get; set; } is a shorthand in C# for creating a property with both a getter and a setter.
It allows you to read and write to the value without having to write full get and set methods manually.
In what situations would I use that for?
Properties have many uses:
They can validate data before allowing a change. They can transparently expose data on a class where that data is retrieved from some other source, such as a database. They can take an action when data is changed, such as raising an event, or changing the value of other fields.
bump
those 2 things seem pretty unrelated
hm yeah i think my friend did a bit of a logic leap
i assume as soon as two physics materials lose contact with eachother they will not inherit any velocity they had from contact
do idraghandler work in non ui gameobjects? if yes, how to make it work in non ui gameobject?
Should work. Implement the interface and make sure you have an event system with he required rwycasters.
It's probably gonna return screen positions though, so it might not work as you expect.
Hello, I'm stuck on how unity works right now. If the image attached is my inspector window, and I have the following code snippets,
how do I rewrite this to work without using SerializeField?
`public class KeyboardController : MonoBehaviour
{
[SerializeField] PlayerController player;
PlayerControls input;
InputAction move;
InputAction jump;
private void Awake()
{
input = new PlayerControls();
}
private void OnEnable()
{
input.Enable();
}
private void OnDisable()
{
input.Disable();
}
void Start()
{
move = input.FindAction("Move");
jump = input.FindAction("Jump");
}
void Update()
{
if (jump.IsPressed())
{
player.Jump();
}
}
}`
`public class PlayerController : MonoBehaviour
{
Rigidbody2D rb;
CapsuleCollider2D capsuleCollider;
private void Awake()
{
rb = GetComponent<Rigidbody2D>();
capsuleCollider = GetComponent<CapsuleCollider2D>();
}
void Start()
{
}
public void Jump()
{
}
}`
📃 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.
o ok
why you dont want to use [SerializeField]
you can set variables on inspector if you mark it [SerializeField] or just type public at the starting of the line
if you dont want it to be shown in inpsector and set it via code, remove [SerializeField] and find object with GameObject.FindObjectOfType<T>() or GameObject.Find()
fields are serialized if they are public or marked [SerializeField]. that's the 2 options you have.
(of course the type has to also be serializable, but that's a separate topic)
(heads up that FindFirstObjectByType<T>() is preferred iirc)
(heads up that serialized references are preferred)
Hey, how can I make unity's particle system to only show one particle rotating? It always emits more than 1 even if I set it to 1 cycle
Since the component is on the same object you can get a reference to it the same way you do for the rigidbody and collider in PlayerController: player = GetComponent<PlayerController>();
ah, i never use it, afaik FindObjectOfType<T>() checks all referances with type T and if it finds, it breaks the loop and returns first element
so idk what's difference between them
it's deprecated, that's the difference
Obsolete: This function is obsolete, use
Object.FindFirstObjectByTypeas a direct replacement or the fasterObject.FindAnyObjectByTypeif any object of the specified type is acceptable.
ah, alr
I don't not want to, I just wanted to learn alternatives, and am learning
ah oke
basically, if you want to set variable on inspector without [SerializeField], you should use public
So is it bad that my keyboard and player controller were coupled together?
Should I have used an event based approach for that?
i mean, if you want to only allow keyboard usage, i suppose this is how you'd do it
but generally that's not a good idea
oh ok
then again, your KeyboardController doesn't actually have anything specific to the keyboard
so just.. rename it lol
ya
so how costly is using a coroutine versus placing an if else in the update method if I want to implement a small cooldown between jumps
not significantly different
I personally do cooldowns by recording time last used but depends on the action that needs it i guess
In my opinion, less about cost, more about stability, with a coroutine, if the behaviour or calling behaviour is disabled, the coroutine will stop running, in which case it might not complete and allow the cooldown to pass, it's more safe to use Time.time for cooldowns, or deltaTime but it's likely less efficient due to appending to a variable every frame rather just getting at time variable and checking the offset between the saved time and current time
Could you elaborate on this? What does "behavior or calling behavior" is disabled mean? Is there an easy example to consider
MonoBehaviour.enabled
Any class inherited from MonoBehaviour has the property
Basically disabling the component that has the coroutine or called the coroutine
If the gameobject the component is on is disabled it will also stop couroutines. Async functions do not do this as they do not rely on a mono to "run"
Oh I see
Thats why the time recording is more reliable for something the user can activate such as a jump:
const float JumpCooldown = 1f;
float lastJump = float.MinValue;
if(lastJump + JumpCooldown < Time.time)
{
DoJump();
lastJump = Time.time;
}
is there a way to mess around with an image's properties (saturation) through code?
probably, but you'd maybe want to use effects/filters/shaders for that instead
Seeing that I want 1 or 0 saturation values, would it be easier to just use custom images?
Doing greyscale in a shader is super easy
If you don't care about accuracy you just add up r+g+b then /3
this is more of a C# question than unity specifically: I'd like to write a generic function that accepts number-like inputs (i.e. floats and vectors), so that operations like T-T and T*(float) are defined. Is that possible?
If I’m going to store the state of a large tile map, how do I go about this? I’m tempted to store the interesting tiles in a dictionary, mapping coordinate to objects on interesting tiles, and then serializing the dictionary to a file. This seems like a naive solution though, does anyone have advice?
Usually for grids we opt to use a 2d array but if it's too large you can split it into many
No. Generic maths is a .NET 7 feature we will not have access to until Unity 7.
Your option is to write all the overloads.
A dictionary with a vector2int key isn't too bad but may not be nice to save and load as you need to avoid duplicates yourself
Hm yes ok! I’ll just stick with something similar for now I guess

thanks for the quick info
As a beginner developer, do you think a bounty hunter game is too ambitious? I want to make a game that has you talk to an NPC, it gives you a quest to kill someone, and once youve done that you get currency to buy better guns and stuff
Do you think I, with little unity experience but lots of tutorials, can pull this off?
yes that's too ambitious
What would be a simpler way to make this? it's my dream game
Stick to something more basic along the lines of flappy bird or doodlejump
simply, no
you'll get more experience as you practice, so it's not infeasible to work to that big goal, but it'll be much easier on yourself to practice on simple things to start, focusing on one thing at a time
Ok, thanks! Ill first learn how to make FP movement and interaction
The reality is that if you try to make your "dream game" right away you are most likely going to fail.
That being said if you are truly dedicated it's fine to get started on it now, but you just need to know it will probably take you years to get it into a state that is actually production ready / sellable.
but yes ideally focus on learning the basics first
ill do this to begin
thanks so much!
I'm getting a NullReferenceException on the line bombScript.LaunchArc(bombTarget) despite Debug.Log telling me neither bombScript nor bombTarget is null. Why else would I be getting a null exception?
bombScript is likely null
unity is kinda weird with null
debug with x == null instead of just x
For basic enemy AI, do you recommend Coroutines or some state machine (not implemented by coroutines)?
does bombScript log as "false"?
Both are logged as false
that means they are both invalid objects (destroyed or null)
also your variable names are confusing, an instantiated prefab is no longer a prefab and an instantiated component is not a script, a script is the c# file from which it is created.
likely your "bomb" prefab doesn't have a "Bomb" component.
But is the code still correct in referencing a script on the prefab called "Bomb"?
it is correct if by 'prefab' you mean 'GameObject'.
so is there any reason it would still come up as null?
inb4 Bomb is not actually on bomb
I checked during runtime it is
...what?
with the == null check, correct?
yes
yeah his response confused me there thought it was the opposite haha
is the line you mentioned, the first line of the stacktrace?
The error is "NullReferenceException: Object reference not set to an instance of an object
Bomb.LaunchArc (UnityEngine.Vector2 targetPos) (at Assets/Scripts/Bomb.cs:17)
Enemy.EnemyBombThrown () (at Assets/Scripts/Enemy.cs:120)"
ok so it's not actually in this script...
look at the line mentioned
Bomb.cs line 17, inside the function LaunchArc
oh yeah your right it is, double clicking it takes me to line 120 in Enemy.cs for some reason
No, checking without == null, false means invalid
it wouldn't be false
it'd be the name of the class
i told them to use == null, so that's where the boolean came from
qn: what is MonoBehaviour? If I want to write a data wrapper class, does it need to inherit this?
no
MonoBehaviour is basically any custom component
it extends Behaviour, which extends Component
any component must extend that, but Behaviour and MonoBehaviour give a bit more stuff to work with
Hey folks looking for a better way to do this jumpscare, Unfortunatly, isVisible is called almost constantly if the object has scene interactions, including casting shadows etc, so it's vanishing before i can even look at it
use a delay maybe
It will need a delay anyway but I dont think that's the actual issue
hard to explain, I'll put the delay in and see where i'm at
I'm making a game with multiple scenes and loading the character customization scene takes about 4 seconds due to all the textures. I'm fine with that so long as it loads at the beginning of the game, but it loads every time you hit the button to go to the custimization scene
is there any way to frontload this
and then keep all the stuff loaded in memory
Okay so the script is somewhat working, the isVisible only gets triggered if i'm looking in the direction of the renderer, however it doesn't account for solid walls
Use MonoBehaviour only if you need to attach the class to a gameobject directly, as a component
why is that? i.e. what does MonoBehaviour actually provide?
(I believe you, I'm just curious)
Lets you make custom components that you can attach to gameobjects
Not all classes need to be that
ah, you mean like fields that appear in the object inspector?
Nah, not fields, components
Stuff you add with the Add Component button
These components can have fields ofc though
But yeah in the inspector
so what are you saying MonoBehavior enables? The ability for a gameobject with a script attached to have components?
The MonoBehaviour is the script attached/the component
You can't directly attach a non-monobehaviour class to a gameobject
So I'm needing some help with transforming the scale of my Capsule shape. I want it to morph into a shorter shape whenever I crouch down.
Here are some variables that may help:
I am very new, beginner to C# in unity.
So, set the scale to the value you want it to be when crouched
What value do you want it to be?
A tool for sharing your source code with the world!
nothing in OnMouseUp() is triggering
Put a log outside of any conditionals and see if the function is running
i did
...and? What was the result
0.50f, but it shows an error whenever I put it.
like this?
Scale is a Vector3. It has three axes. What values do you want for each axis of the scale
like i said before
there was a Debug.Logoutside conditionals before u suggested it
Okay, usually a good idea not to remove code and then expect me to assume you had code there before.
Show the inspector of the object with this script on it
dude
I am so bad at this I am so sorry
it was there the entire time
I've been trying to study without real help and feedback.
This is my very first time with live help.
Scale is not a function. Set the scale to a vector.
Ah, fair, that's on me. On mobile the line above wrapped twice and I didn't notice the } between em
No collider
How do I do that?
new Vector3
Ooooh.
also i tried adding a collider, still didnt work
okay, so no errors. but is this correct?
"Not over the same collider it was pressed on" != "This does not require a collider"
OnMouseUp sends to the collider you are hovering over when you release the button
You've made the vector but you're not doing anything with it. You probably want to assign something to that value
hmm... hows about this?
is your object by any chance in ignoreRayCast Layer ?
Yes, try that out, see if those numbers are what you want
no, just the default
Thank you! I will test.
why is crouch an axis
do you have a collider2d that is check isTrigger on the object ?
Note:
for OnMouseUp
This function is called on Colliders and 2D Colliders marked as trigger when the following properties are set to true:
For 3D physics: Physics.queriesHitTriggers
For 2D physics: Physics2D.queriesHitTriggers
OnMouseUp can be a co-routine. Simply use the yield statement in the function. This event is sent to all scripts attached to the Collider.
this fixed it
thanks
Changed my input system (started a new project) will test.
hmm... my character won't move now...
none of ur functions are ever called/used?
Ooooh.
So I have void Update()
then I have every other method inside of that. is that why?
declaring the methods inside of Update does not mean they are invoked anywhere. you need to actually call the method
so theres:
void Movement
void Crouching
and void JumpAction
oh okay.
How do I do that?
there are beginner c# courses pinned in this channel, you should start there
also unless you know why you are nesting methods inside of other methods, you really shouldn't so you can avoid potential issues
Thank you for the guidance, I will use this to continue. (the courses)
I feel like someone heare made skibidi toilet sim Hnn mmmmmn
I figured it out now. Now I know what Declaring and Calling a variable/method means.
I downloaded Simple Rewards System by Coppra Games in the assets store. The claim button and close button are linked up but neither of them work. Could it be because the button I made to open the daily rewards also closes and opens the daily rewards panel?
Hello i am making my first mobile game but i am trying to find how to make input on mobile (like subway surfer so without buttons) but i only find tuto on how to make mobile input but with button on the screen
!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
OMG I DID SOMETHING
I made it to where if I press the crouch button, it crouches and when released it goes back up
I am proud of myself.
your camera follows your mouse, right? and what is the first thing you typically do after clicking the play button? that's right, move your mouse in a downward motion to the game view
it's not something to "fix" because it's literally your camera following your mouse movement, you know, the thing your code makes it do. if you don't move your mouse after clicking the play button you'll see that doesn't happen
Like look this is whats happening
yes, i just explained exactly why that happens.
man
"guys my first person camera rotates downward when i move my mouse downward which is exactly what i want to happen but why is it happening"
what script are you using.
there's not an actual issue, they just for some reason are not understanding that upon pressing the play button their code is tracking the mouse movement to move the camera. they would see it rotate horizontally if they instead moved the mouse left or right instead of down immediately after pressing the play button
yeah, but his video shows that it starts with a snap down looking down. i don't remember experiencing that with my CameraLook.cs script
because they move the mouse down immediately after pressing the play button. that first frame has already started by the time they move the mouse down
because the mouse moves down quite a bit within the first frame
i think both of you are blind 🙂
i assure you, this is exactly what is happening.
we see what's happening. we also see the thing that's causing it to happen
they can test it themselves by doing exactly what i said before and not moving the mouse after clicking the play button
We'd want to see the camera orientation if they had not moved the mouse at all when clicking the play button.
@inland temple show another video
i know why
its because im inside of unity cause when i exported the project it didnt happen
okay
again, it's because you press play in the editor which starts the first frame and then you immediately move the mouse so naturally when that first Update happens and your code tells the camera to follow the mouse's movement from that frame, it does exactly that and moves the camera in the direction you moved your mouse during that frame, which again, started as soon as you pressed the play button
it's because you moved your mouse down
cause im working on a psychological horror game
that isn't particularly relevant
you work in a lighthouse and a creepy guy follows you to the lighthouse
i know
ok we don't need to hear this story
julius good luck with your game!
do you want to figure out the "issue" or not lol
i did
it's not because you were in the unity editor, no
thanks if you are working on 1 to good luck aswell
Thanks. I'm working on a Contra-3 clone, and I recently gave up because player can get stuck in moving platform sometimes.
Uh, that didn't work
use mp4 to embed in discord. but also if this is just to show off your work, then post in #1180170818983051344
this is also not a social-hangout server #📖┃code-of-conduct
Are we really hanging out right now? You're making this worse, I feel.
kinda polluting the channel here
this is a help channel
we don't exactly have chat here, you're free to open a thread in #1180170818983051344 or something if you want to do so
If I have a tilemap, with say grass on it, and the player can interact with it to turn it into plain dirt, is it cheaper to render all layers and just hide the layer that’s been “dug up” (I.e. render grass on top of dirt), or is it better to just change the actual content of the tile
i would imagine that it would be cheaper to just change the tile, but you'd really have to profile it to determine any performance impact of either solution
make something that works and makes sense first before worrying about optimization

keep layers
otherwise you'll fall into "premature optimization" and you'll end up spending more time on "optimizing" (that may or may not be relevant) than implementing stuff lol
make it work first, make it good later
Hey folks coming back to this now, Does anybody know if there is an easier method I'm not seeing to solve this issue, or should I just switch to raycast
I don't understand this part of your original message "looking in the direction of the renderer". It sounds like the renderer is an object, but to my understanding, the renderer is the core of unity that displays the screen.
A renderer as in ' a mesh renderer etc'
Attached to an object
As a beginner developer, does anyone have any cool and unique game ideas that I could practice? Like, a simple game to learn code and stuff?
Yes, I can DM you something
ok!
Mesh renderer's isVisible isn't precise enough for that kind of thing. Raycasting is the usual solution
It would have worked perfectly but it just doesn't account for other mediums like walls in the way etc. Unfortunate
if(Random.Range(0, 100) <= 100 - BadLawSpawnChance)
The variable is set to 25 which should mean that the if Statement is true 75% of the time and 25% its false but after testing its closer to being true 32% of the time. why??
how are you actually confirming that percentage? and more specifically, what is your sample size? because RNG like that only tends to trend to the expected percentages with very high sample sizes
hey folks, would anybody know why this doesn't seem to be deleting the monster when looking at it,
Range is set to 10, and i can walk inside of it
use the CompareTag method rather than string equality to check an object's tag. but also throw some logs in there to make sure that not only is your code running but you are hitting what you expect to be hitting
it was like 10000/3250 or smth I made the text display the ratio
I assume thats like
if (hitInfo.collider.CompareTag("monster"))
Threw in a debug and it spat out this
well yes, now you check the tag of the hit object regardless of whether anything actually was hit
You're using hitInfo regardless of whether your Ray hit anything. You should probably put that in the if
I think its a problem with randomness not being random
So I noticed the monster was flagging as invisible... I didnt have any form of collider on it lol
it seems to be fixed
Humans are notoriously bad at understanding randomness. 32 hits on a 25% chance is not that far out of the realm of possibility. Try running like a million of these
you've still not actually said how you tested this
i ran like 10k
Yeah, I was trying to fetch a ray collision on an object without a collider on it (dont be like me) 🧠
if > 75 then x + 1
else y + 1
y/x = 32.5%
christ, if you aren't going to provide the actual information then i'm just not going to help you
Okay, now run it a million times and show what it prints
Also, this should be giving you about 33%
You're comparing hits to misses not hits to total
25 is one third of 75
Now i'm really lost, I can't get the audiocontroller to play the sound in this location
If i put it on the after below setactive, I get cannot play a disabled audio source
Audiosource is set to 2d and full volume
No errors in console I just dont hear it
Do you get your log messages
Yeah
I get the before and after
so obviously an issue with this audiosource
Is the duration zero?
Then the sound is playing. Is your audio sources close enough to an audio listener to pick up on it? Do you have sounds enabled in your game window?
after 100k times it seams to approach a ratio of 24.5 consistently which is interesting but close enough for me
(i am stood infront of the sound source anyway)
Remember that random range is max exclusive, so 0,100 can only ever get as high as 99
that would explain the .5%
where are you starting the coroutine
Logic = once you look at monster = spooky sound then 1 second later monster gone
every single frame that those if statements are true you start a new instance of the coroutine which means Play is called on the AudioSource again, each time Play is called on the audiosource the sound starts over
yes, but because you start it over every single frame it never actually has a chance to play it
I see what you mean, Trying to think of a solution
make a bool?
to say if it's happened?
You could cache the coroutine and only start the coroutine if not started (is null etc)
This seems to be functioning how I need