#💻┃code-beginner
1 messages · Page 129 of 1
() to call a method
.GetComponent<NavMeshSurface>();
but also, just make your navMeshObj variable a NavMeshSurface. you don't need to reference the GameObject just to call GetComponent on it, just reference the component directly
On line 12 put a [SerializeField] infront of private
I want to do that yes but I cannot drag a component from another object to a public variable field right?
yes you can. that's literally what i suggested to do
Public or private with a [SerializeField] it doesnt matter
Unity would be really miserable to use if you couldn't do that.
You can drag any unity object into a serialized field
An object yes, but not a component that sit on another object. boxfriend is saying that we can but I dont see how.
a Component is an Object
what is it?
Isn't a component part of an object?
every Component must be attached to a GameObject
perhaps that's what you're thinking of
No matter what i set the gravity scale to the bomb explosion makes the character fall at a really fast speed
Ha ok I thought object = GameObject, I come from Blender so that kind of made sense but I see the difference now.
UnityEngine.Object is the big parent type.
I know this is simple as hell but i can not figure out how to fix it
also notice, I wrote Object, case matters
and how does the bomb work?
sounds like you need to look at PlayerMovement, then
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
share the entire script in a paste site
the player movement script, I mean
If gravity scale isn't doing anything, then there must be something else changing the player's velocity
Ok I finally understand that by dragging a GameObject to a public variable initialized to a specific type it figure out by itself that I want the component of that type on that GameObject. Is that correct?
I know im just sharing both for context
Yeah, you can drag the GameObject in and it'll grab the first matching component
You can also drag a specific component, but that's more annoying, since you need two inspectors up (unless you're dragging between two things on the same GameObject)
Cool, thanks everyone
I almost never store GameObject references
only when I literally just want to turn something on or off
Yeah it would have felt annoying to reference a GameObject and then have to get the component on that GameObject within the script
I'm glad this work this way it's much easier
If your gravity scale is zero, you should just fly into the ceiling. Does this not happen?
Yeah to kept trying to drag the actual script component from other game objects into the inspector, being able to just drag the object itself is a lot nicer
ah, yes, that'll do it
Theres an animation event i realised once he was actually in the air
I want to update the NPC's name with the name given to it. How do I do that?
This is the default
whats the playstations share button called in the new input system
my scriptable item script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "Item", menuName = "Scriptable Objects/Item")]
public class ItemSO : ScriptableObject
{
public string name;
public string description;
public Sprite icon;
public GameObject prefab;
public enum ItemType
{
Resource,
Tool,
Weapon,
Consumable,
}
public int stackCurrent = 1;
public int stackMax;
}
when an object is picked up using another script, it collects the ItemSO info on that item, which then I can add it to the inventory (have to remake this)
i dont have the skills to help you with this i just restarted making game with unity after a few months
yea im pretty new too, started maybe a week or 2 ago
also can anyone rate this code for me?
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
using System.Collections.Generic;
[System.Serializable]
public class LevelData
{
public int ID;
public string Name;
public GameObjectData[] gameObjects;
}
[System.Serializable]
public class GameObjectData
{
public int id;
public float x;
public float y;
}
public static class LevelManager
{
public static void SaveLevel(LevelData levelData, string LevelFilePath)
{
string dataPath = Application.dataPath;
string levelDataPath = Path.Combine(dataPath, LevelFilePath, ".dat");
List<LevelData> levels;
if (File.Exists(levelDataPath))
{
BinaryFormatter Bformatter = new BinaryFormatter();
FileStream stream = new FileStream(levelDataPath, FileMode.Open);
levels = (List<LevelData>)Bformatter.Deserialize(stream);
stream.Close();
}
else
{
levels = new List<LevelData>();
}
levels.Add(levelData);
BinaryFormatter newFormatter = new BinaryFormatter();
FileStream newStream = new FileStream(levelDataPath, FileMode.Create);
newFormatter.Serialize(newStream, levels);
newStream.Close();
}
public static List<LevelData> ReadLevelFile(string LevelFilePath) {
string dataPath = Application.dataPath;
string levelDataPath = Path.Combine(dataPath, LevelFilePath, ".dat");
List<LevelData> levels = new List<LevelData>();
if (File.Exists(levelDataPath))
{
BinaryFormatter formatter = new BinaryFormatter();
FileStream stream = new FileStream(levelDataPath, FileMode.Open);
levels = (List<LevelData>)formatter.Deserialize(stream);
stream.Close();
}
else
{
Debug.LogWarning("Level data file not found.");
}
return levels;
}
private static void _LoadLevel(Scene scene, LevelData levelData)
{
if (scene.name == "Level")
{
foreach (GameObjectData goData in levelData.gameObjects)
{
GameObject prefab = Resources.Load<GameObject>(new string("Prefabs/GameObjects/GameObject_" + goData.id.ToString()));
GameObject go = GameObject.Instantiate(prefab, new Vector3(goData.x, goData.y, 0f), Quaternion.identity);
}
SceneManager.sceneLoaded -= (scene, mode) =>
{
_LoadLevel(scene, levelData);
};
}
}
public static void LoadLevel(LevelData levelData)
{
SceneManager.sceneLoaded += (scene, mode) =>
{
_LoadLevel(scene, levelData);
};
SceneManager.LoadScene("Level");
}
}
simple 2d level manager for user made levels
Well for starters dont use binary formatter. Its deprecated by microsoft and poses a security risk.
anything else i shuld change?
Does this code work?
Use using statements when dealing with file streams, so they're closed automatically even if you return early or an exception occurs
it worked years ago beford i abandoned the project
not years
So does the code work?
like 10 months
i can check
I cant compile the code in my head, if it works it works. You might want to look into using the adressables system rather than loading objects from the resource folder, use a proper GUID rather than a id in the name of the object and I dont like the _ in the method name since it does not follow convention
how do i have it log it just once and have it update the log msg for however many seconds the button is pressed
Also, you can have same named functions provided their parameters are different (as with your two LoadLevel functions)
You dont
i can give u the project folder but there is a huge amounts of problems with the plkayer movement
Lambdas don't need braces where there is only a single instruction in them
SceneManager.sceneLoaded += (scene, mode) => _LoadLevel(scene, levelData);
dang
You can toggle collapse in the console window and then then same msg will have a counter
but anyway the only usefull part is loadlevel cuz the rest has security risks
You also cannot unsubscribe the lambda from the event with -= as even if the lambda is written exactly the same, it's still two different instances of it
The unsubscription does nothing
yes -- it does reference equality, iirc
I usually just write a named function at that point.
(it can still use the => syntax!)
Although, this won't work if you need to capture some local variables for that lambda.
How would you distribute points randomly on a mesh surface? I'm trying to spawn entities on the navmesh according to a set density per square meters. Is there a built in function for this somewhere?
I found this answer but this seem like a lot of code for something so ubiquitous in video games. https://community.gamedev.tv/t/good-way-to-dynamically-and-randomly-spawn-on-navmesh/230492
I’ve been messing around with means of randomly spawning an object on Navmesh. In my use case I don’t want to spawn something as close as possible to a certain spot on a navmesh. Rather I want to spawn something within a predefined radius. This is what I could come up with. I was worried it was going to be extremely inefficient but spawning ...
This makes more sense though: https://docs.unity3d.com/ScriptReference/AI.NavMesh.SamplePosition.html
Still it's not ideal but whatever.
how do i make function that edits existing variable rather than putting it inside function
like string.replace
Replace returns a new string, it does not edit the string you pass in-place
yes just i put it variable.function not function(variable)
The answer is, it depends on the type of the variable you need to modify
what
Well to be able to do that, you need to add the method inside of the type (in the class)
Then you'll be able to call it on an instance of that type
doesn't seem like a ton of code to me
uniformly choosing from a point on an arbitrarily complex mesh isn't easy
You can pick a random triangle from the mesh and then pick a random point in that triangle
but that's biased towards small triangles
technically how transform class works rather, more like matrix3x4 and using transpose and other similar methods. Self-modifying methods that would be private.
I guess you could add up the areas of all navmesh triangles, then use those to do a weighted random choice
it's how a lot of things work :p
foo.Bar() is calling Bar on whatever object foo contains
Yeah, if you're asking how to add a method to an existing type, that's the way to go
hi why unity keeps giving me this error? NullReferenceException: Object reference not set to an instance of an object
CollectableInteraction.StartInteraction (UnityEngine.Transform objectToInteract) (at Assets/CollectableInteraction.cs:64)
CollectableInteraction.Update () (at Assets/CollectableInteraction.cs:35)
NullReferenceException: Object reference not set to an instance of an object
CollectableInteraction.StopInteraction () (at Assets/CollectableInteraction.cs:88)
CollectableInteraction.Update () (at Assets/CollectableInteraction.cs:26)
my code works fine.
its very annoying
Show the !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
You could weight it by face area but yeah it gets complexe for no reason at this point. I think that's why everyone is just raycasting. Edit: nvm thats what you said just after lol
vfx graph actually has a built in method called point caches but I'm not too sure of the usability out side of it
Randomly picking points until once is on the mesh will give a uniform distribution, yeah
It'll also take a random amount of time, so it's not perfect
(we'd call this "rejection sampling")
https://docs.unity3d.com/Packages/com.unity.visualeffectgraph@10.5/manual/point-cache-bake-tool.html
Pretty cool tool they should just make standard
i still dont understand how to fix that lol
what about that do you not understand
also don't copy the raw link when sharing these links
i dont know how to fix the actual code https://gdl.space/uducayupoz
why doesnt this set it to 0.0?
hey guys. i have it if val1 or val2 are null my function returns false, but im still getting a null refrance exception. why is that?
because you immediately set it to Time.deltaTime in the next if statement
but it doesnt go back to 0 before starting again
The log does that. It's before the if statements
because you immediately set it to Time.deltaTime in the next if statement. in the same frame
if timer is true, set timer to false and timePassed to 0. then you immediately check if timer is false
If you Destroy() a gameobject that has child gameobjects, is Destroy called on the child gameobjects? Or are they garbage collected later on? What happens to the child gameobjects?
oh, sorry, guess my brain was also getting a null reference exception when searching for whats wrong in my code lol
they are destroyed as well, yes
The stack trace includes the line number:
MemoryVariable.cs:10
Line 10. All that's left is to look at what's on that line
ill keep that in mind for next time. thx
this check 'if (timePassed == 0.5f)' will never be true
It can be true, but it's unlikely
No necessarily never, but extremely inconsistent
weeeeeelll ok, sure, some people do win the lottery
if you want to be pedantic about it 😄
Way better odds than the lottery. It can be true pretty frequently actually
im trynna make it log it only every half a second
that's not a discussion worth my time
= if adding <= if subtracting
I never saw the actual code
Haha actually you'll hit 0.5 if you get 30 frames at exactly 60 FPS, ignoring the float precision issues
that's a big thing to ignore 😅 but yeah, the math works out
eh, maybe 10-15 ways? a trillion ways to not get it. also, you only get one chance to check, and that check is also based on user input
im trying to hold the button and have it only log once every half a second but this time its instantly going to 999
ya need to add some time contraint otherwise you're probably logging every update loop
look up timer tutorials or how to set a cooldown
do I need to open a ticket to ask a question?
No. This is not an official support discord
can someone help me figure out why the player's velocity gets set to 0 when i touch the ground after falling? and why I get stuck with my head when I touch the platform?
show your code
i do be setting gravity to 0 when on ground so i wont be constantly rolling down on near flat surfaces
i mean x velocity
perhaps too low terrain bounciness
this is the code, most of the variables are in italian tho , i can tralsate if oyu need claryfying
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
oh sry
how do i set it ? it's grayed out in the box collider
make new physic material and drop it on collider material
public void TakeDamage(float damage)
{
Debug.Log("TakeDamage");
if (playerController.isBlocking)
{
damage = damage / 4;
}
else
{
currentHealth.Value -= damage;
animator.SetTrigger("Hurt");
Debug.Log(damage);
if (currentHealth.Value <= 0)
{
Die();
}
}
}
so i get the first debug but i dont get the second anyone know why i also dont deal damage
if i set the bounciness higher the player just keeps bouncung infinetly higher
your else statement is never hit
if you do not get the second debug then either you are receiving an error or playerController.isBlocking is true
i tried without the else statement because i dont need that i only added it because it wasent working
something is not working you just throw something else and hoping it works?
debug your original problem then
what does "wasnt working" mean in that context
Hey, guys! I don't know how to set my default screen resolution to my in game resolution when entering the game. How to do that because when I am entering the game I don't see my screen resolution. I made a dropdown for my resolution options and I save them and load as well but the only problem here is to load my default resolution, so the players screen resolutions to its default screen resolution of their monitor inside the game.
Check my code here:
{
// Every variable or initialization that has to happen when the game starts in here!
resolutions = Screen.resolutions;
if (resolutionDropdown != null)
{
resolutionDropdown.ClearOptions();
}
List<string> options = new List<string>();
for (int i = 0; i < resolutions.Length; i++)
{
string option = resolutions[i].width + " x " + resolutions[i].height;
options.Add(option);
if (resolutions[i].width == Screen.currentResolution.width && resolutions[i].height == Screen.currentResolution.height)
{
currentResolutionIndex = i;
}
}
if (resolutionDropdown != null)
{
resolutionDropdown.AddOptions(options);
resolutionDropdown.value = currentResolutionIndex;
resolutionDropdown.RefreshShownValue();
}```
like i didnt get the debug or take damage
did you debug your playerController.isBlocking values
also i was talking about the issue before you changed it
The stuff in the else only runs if the stuff in the if didn't run.
So if you have blocking enabled, you don't receive damage. You divide the value by 4, and execution exits the method without running anything else
Your code editor might even tell you that damage = damage / 4; can be removed as damage is never read after that
I don't see any debugs here, that should prob be your first step
Online compiler does it, so your code editor will also tell you:
(code adapted to compile without Unity)
well i know that the blocking is false
because if its true it has a animation
Terrible way to do that. The animation transition may be broken, or the logic isn't quite what you expected, or something else.
Use debug.log or a debugger. Distrust EVERYTHING else
yeah but wouldnt just removing the else fix the whole problem with the if else
Yes, I mean how to set my resolution when the game starts like when Made with Unity is showing up to my monitor resolution? Because when I start the game it doesn't set my monitor resolution to the game resolution. I was wondering if I have to use something like Screen.SetResolution() on the awake function?
Maybe, maybe not.
You tell us, IS it fixed?
well it didnt work before
That's not what I asked.
Does it work now
its possible but first make sure, is the function even working as is ?
no
Then removing the else didn't fix it, right?
no it did not
Isn't that the default behavior? When you run the game for the first time the default is to fit to the screen, no?
In the past there was the launcher window where you could change the quality and resolution, but that's gone now. I'd check your project settings
i found the issue
public void TakeDamage(float damage)
{
Debug.Log("TakeDamage");
if (playerController.isBlocking)
{
damage = damage / 4;
}
Debug.Log("damage: " + damage);
currentHealth.Value -= damage;
Debug.Log("currentHealth: " + currentHealth.Value);
animator.SetTrigger("Hurt");
Debug.Log(damage);
if (currentHealth.Value <= 0)
{
Die();
}
}
i get all the debugs up till after i change the health value
So, how to use that attribut?
did you look at the second link ? it shows how
So, you still get the first debug and not the second.
Can you show the whole current code
Do you get errors in the console? Code doesn't stop executing out of the blue like that! Make sure errors are enabled in the console
So, I have to make a method and before that method to add that attribute is says?
using UnityEngine;
class MyClass
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSplashScreen)]
static void OnBeforeSplashScreen()
{
Debug.Log("Before SplashScreen is shown and before the first scene is loaded.");
}
}```
I was always working with methods I dont know what those attributes is, I had no time to work with them and learn them actually.
it usually goes above class/method/member var
ok!
https://docs.unity3d.com/ScriptReference/Serializable.html
this one you mean or this one
https://docs.unity3d.com/ScriptReference/SerializeField.html
There is no method for that functionality? I mean there are only attributes?
the attribute is what tells the method to run before scene load
I was searching for OnApplicationEnter maybe but there is no method called like that XD
but as SPR2 mentioned, resolutions is usually set to default when running the app first time no?
Oh, it seems cool thanks for the information!
unless you changed it in Player settings
Here I mean the second one the field one
Why do people use Empties as root in Prefabs? This seems so bad to access Components or public variables on scripts
Its to Split Logic from visuals for better structure
@rich adder Do we use attributes only for static members?
how does that at all affect anything (variables and components)
the components actually go on the root
only GFX get split up
Ever used [SerializeField]? You have your answer
apparently they have and still asked 😆
You can Access all the components If you need them
With a serialize field or GetComponentInChildren
What about colliders. Do you leave them on meshes?
if its a mesh collider I usually do, esp if my mesh has resizing
otherwise you get bad sizing
simple shapes i keep on root
so i just modify their size with gizmos
Also helps keeping uniform objects when the prefab is rotated. If you try to do that with a root object that's scaled, it will seriously affect its children
Store the whole color in a variable, modifiy its alpha, then assign the whole color back to the material
ty
So I can't serialize this one that easily, right?
what is "this one"
prob screwed with the reference types
This one is the list of quite a data... so I can't just give the refference to the list to data saver and hope it will just save it?
Yo! I have a problem. I have an empty game object (a pivot) and I childed a Camera on it. When I'm not in play mode, when I rotate the pivot the camera rotate around it like supposed, but when I'm in play mode it doesn't work. I don't understand why it makes no sense, and I didn't find any solutions on the internet. Can you help please?
(don't scale mouse delta by Time.deltaTime)
Why ?
References afaik are a pain to save
could be wrong
maybe use scriptable objects??
Addressables are prob an option too since that assigns an actual address to the asset @visual hedge
I have to look back into its been a while xD
sorry, I think I might express myself wrong:
I have a list of different type of data, here's the screenshot.
And to save that list, I just be like:
public List<CapturedPets> summonList = new();
summonList = character.summonHandler.SummonList;
sorry so whats the problem? is it not serializing ?
I guess I may have done something wrong anyways but it seems it doesn't save... throws a long error in the console.
what is the error?
1 min, let me try once again 🙂
C# question here:
Does children classes inherit the complete classes' methods without overwrite it from the abstract class? If not, what should I do to accomplish this?
its probably GameObject ? idk if unity likes saving it @visual hedge
Yes, they do, as long as the methods themselves are not abstract (the compiler will force you to override them in the derived class anyway)
A child class has access to all its base members, provided that they're accessible (protected or more accessible)
And the script is on the pivot
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class SceneObject : MonoBehaviour {
public int sequenceID;
private void Start() {
gameObject.GetComponent<MeshRenderer>().enabled = false;
gameObject.GetComponent<Collider>().enabled = false;
MainProgressManager.mainProgress.OnNPCArrive += Called;
MainProgressManager.mainProgress.OnSelfDestruction += SelfDestruction;
MainProgressManager.mainProgress.OnStartUp += StartUp;
}
public void StartUp() {
if (sequenceID == 0) {
gameObject.GetComponent<MeshRenderer>().enabled = true;
gameObject.GetComponent<Collider>().enabled = true;
}
else {
gameObject.GetComponent<MeshRenderer>().enabled = false;
gameObject.GetComponent<Collider>().enabled = false;
}
}
public void Called() {
int progressPhase = MainProgressManager.mainProgress.progressPhase;
if (progressPhase == sequenceID) {
gameObject.GetComponent<MeshRenderer>().enabled = true;
gameObject.GetComponent<Collider>().enabled = true;
}
}
public virtual void SelfDestruction(int progressPhase) {
if (sequenceID < progressPhase) {
gameObject.SetActive(false);
}
}
}
okay, I guess it doesn't ) thank you
here is my abstract class, so that my child classes will automatically have the called and startup methods subscribe to the actions? Because it seems that it is not the case or I'm doing something wrong
If the child also declares a Start() method, the base will not be called. Make it virtual and call it in the override
there are a couple threads on this subject, afaik if you need to save GameObject reference something is wrong with the structure
oh I see, that is the problem my Start() method in child overwrites it.
wrong is the fact that I am noob 🙂 And I try my noobish approaches and well... that leads to problems
So make the base method virtual, when my child override the method that will be addition to the method, right?
whats the difference between writealltext and writealltextasync?
haha we live n we learn
one is async and one is not
Yes, just make sure to call base.Start() in the override. Your code editor will add that automatically, don't remove it in your case
yh but what does that mean in use lmao
better question you should ask is , what is async ?
yhh
I got rid from game objects in that list and still got an error...
sorry
async is when you want the code to run parallel to other code or in the "background"
so it doesn't block the main thread
eg if you have a long list of stuff to get from the internet, you don't want your UI locking up while loading all that data downloading
so think of it as "run this in the background"
Writing to a file can also take time so its best to use async to not lock up the UI
most UI in any app run on the main thread
OK this is likely a dumb question, but how can you easily view the position of each vertex of a mesh?
I want to look at a mesh and know, mesh.vertices[0] is here, mesh.vertices[1] is here, etc.
so i have a piece of code that is supposed to launch the player backwards and a little bit upwards upon dying, as well as rotating the player 90 degrees. i think it might work for the most part, but the problem is that the player proceeds to clip through the ground when flipped, and i don't know why. the game is in 2d
if (isFacingRight) { rb.AddForce(Vector2.left * 15, ForceMode2D.Impulse); rb.AddForce(Vector2.up * 10, ForceMode2D.Impulse); transform.Rotate(0, 90, 0); } else { rb.AddForce(Vector2.right * 15, ForceMode2D.Impulse); rb.AddForce(Vector2.up * 10, ForceMode2D.Impulse); transform.Rotate(0, 90, 0); }
they're pretty useful the more you get comfortable with them, ofc you don't want start using it everywhere because you run into other problems
Yhhh I’m thinking to use it for my save system for now and since that’s the only place I would really be writing any data to a file I think it would be useful
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PathObject : SceneObject {
private NPCManager nPCManager;
public override void Start() {
nPCManager = FindObjectOfType<NPCManager>();
MainProgressManager.mainProgress.OnCallNextPath += ReturnPath;
}
public void ReturnPath(int progressPhase) {
if (progressPhase == sequenceID) {
nPCManager.moveTo = this.gameObject;
}
}
}```
but still the gameobject attach to the child script doesn't disable its visual on Start()
You missed calling base.Start() -> #💻┃code-beginner message
Yeah writing to files is def good use of async since it can take a second or maybe more depending on amount of data and other factors
unity has an entry point for async in awake too, which is useful @knotty gust
Wdym?
What other factors would affect it if you don’t mind explaining
you know the method Awake ?
private async void Awake()
{
await Task.Delay(1000);
//wait a second and move on
}```
Ohhhhh fr??
the amount of data you're writing, hard drive speed anything that can affect writing to a file
Damn so I didn’t have to use a coroutine for delays on awake?
Ohhh ok that makes sense
Thank you
depends, usually best to use Coroutines because they are already part of unity workflow
Coroutines are poor mans async
Makes sense looking at it now
So when would using async awake be better than coroutines?
if you're for example doing an Init operation from the web
Yhhh I’m Ngl idk what an init operation 😂
like cs private async void Awake() { await LoadSaveClass.LoadSomeWebData() }
not only but thats a pretty common usecase
since data from web is not instantanious usually
Why’s it better to use async awake for that?
Yh I thought it would be Smth like that
Like I said earlier, so your whole application doesn't lockup while fetching data
particularly UI
yes
they're both async methods
unity recommends using this though when using async
https://docs.unity3d.com/2023.1/Documentation/ScriptReference/Awaitable.html
Should I use Rigidbody.velocity or Rigidbody.AddForce() when making a movement system? I know you shouldn't change the velocity directly, but I see it being used in movement systems a lot.
Why do you think you should not set velocity directly?
And use either.
Try both and see which feels right to you. They can feel fairly different, so it depends on the game
Thanks a lot! Also, unity docs states, "In most cases you should not modify the velocity directly, as this can result in unrealistic behaviour - use AddForce instead..."
If you make unrealistic movements (too realistic is sometimes bad) it's perfectly fine to change the velocity directly
What's not fine is changing the transform.position directly with a Rigidbody on, it ingores the physics system!
anyone know what this error means
InvalidOperationException while executing 'performed' callbacks of 'Player/Attack[/Mouse/leftButton,/XInputControllerWindows/buttonWest]'
UnityEngine.InputSystem.LowLevel.NativeInputRuntime/<>c__DisplayClass7_0:<set_onUpdate>b__0 (UnityEngineInternal.Input.NativeInputUpdateType,UnityEngineInternal.Input.NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate (UnityEngineInternal.Input.NativeInputUpdateType,intptr)
and can i ignore it or no
are you using new input system
yeah
This error will be paired up with another error in the console usually
seems like something u should not ignore then
it is paired with another errror
InvalidOperationException: Client is not allowed to write to this NetworkVariable
Unity.Netcode.NetworkVariable1[T].set_Value (T value) (at ./Library/PackageCache/com.unity.netcode.gameobjects@1.7.1/Runtime/NetworkVariable/NetworkVariable.cs:78) MultiplayerHealth.TakeDamageServerRpc (System.Single damage) (at Assets/MultiplayerHealth.cs:64) MultiplayerHealth.TakeDamage (System.Single damage) (at Assets/MultiplayerHealth.cs:55) MultiplayerPlayerController.Attack (UnityEngine.InputSystem.InputAction+CallbackContext ctx) (at Assets/Scripts/MultiplayerPlayerController.cs:242) UnityEngine.Events.InvokableCall1[T1].Invoke (T1 args0) (at <61f56803c0b0466195d97f1cb7494aa1>:0)
UnityEngine.Events.UnityEvent1[T0].Invoke (T0 arg0) (at <61f56803c0b0466195d97f1cb7494aa1>:0) UnityEngine.InputSystem.Utilities.DelegateHelpers.InvokeCallbacksSafe[TValue] (UnityEngine.InputSystem.Utilities.CallbackArray1[System.Action`1[TValue]]& callbacks, TValue argument, System.String callbackName, System.Object context) (at ./Library/PackageCache/com.unity.inputsystem@1.7.0/InputSystem/Utilities/DelegateHelpers.cs:46)
UnityEngine.InputSystem.LowLevel.<>c__DisplayClass7_0:<set_onUpdate>b__0(NativeInputUpdateType, NativeInputEventBuffer*)
UnityEngineInternal.Input.NativeInputSystem:NotifyUpdate(NativeInputUpdateType, IntPtr)
ahh
yes
clients cannot write to Network variable
unless you set permissions to all
idk how thats related to input tho xD
i didnt think network variables could have perms set to all
New Input System also catches the errors that happen in your event handlers, so they're reported twice.
Once for the exception itself caught by Unity, and once for the Input system itself catching it
and im not im using a serverrpc
Well, that is fair then haha. Setting velocity is pretty common though
If I've used an image from somewhere that requires attribution in the project is there a suggested place for that kind of thing? This is an academic project so I've got to write a documentation too if that kind of thing can be linked in the written part if anyone knows?
yes. example
public NetworkVariable<ulong> ReconnectionKey = new NetworkVariable<ulong>(default, NetworkVariableReadPermission.Owner, NetworkVariableWritePermission.Server);
I see, thanks!
i fixed it i forgot to change the write perms to server
text file in the final build should suffice
Of the unity project?
Or the documentation
depends what you're distrubuiting
if the image is part of the docs then yes link to original license/attribute
Ah I'm using it in unity rather than the doc so I wasn't sure where to put the link
in the final build folder with exe, as a text file or if you want a Credits page on your app
Ah alright cool Ty 🙂
Sorry quick question with that first option, is that bit when you go through the build settings?
no I mean just make a text file like you would any other way, paste the link and attribution there
can't you just flip the sprite? And also, I think you can just make isFacingRight and int and multiply Vector2.Right by it
then when you build the game , put that inside the build
how do you prevent the default action for gamepad buttons
my playstation button on my controller opens steam
Unity is not in play mode but I am getting this like every frame
NullReferenceException: SerializedObject of SerializedProperty has been Disposed.
Probably an editor bug
Ignore and move on unity does that sometimes
ok
dont ignore it, just restart it
it'll vanish until the editor bugs out again
usually you can spot unity errors by the way they are..
they'll usually have a specific namespace
like Unity Editor. blabla
= editor bug (not ur fault)
unlike the previous error (this one is ur fault)
that's not always the case though. for example, writing editor code could lead to UnityEditor related errors
thats true..
but if its an unusual error.. (ur not working with editor scripts etc) + seeing that library.. then most likely bug
gyro and accelerometers are both inputs i can use w/o having that allow permissions pop up?
getting started with mobile and walking into a whole new world 😅
I restarted it and found out it happens after I exit playmode every time I add/remove an inventory slot.
When an inventory slot is added (ex: from 1 to 2) I have a set thing that updates inventoryLimit = value and also calls updateInventorySlots() which I suspect is the issue however the methid is called on awake and has no issues when I exit playmode. I wrote no editor code either
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hey,
This is my code to move my character:
moveDir = transform.forward * vertical + transform.right * horizontal;
rb.AddForce(moveDir * moveSpeed * Time.deltaTime, ForceMode.Force);
I get this message above the moveDir on the second line:
Re-order operands for better performance
How may I re-order the code to get better performance?
I believe vectors should be multiplied at the back and floats at the front
i think u can just do rb.AddForce((moveSpeed * Time.deltaTime)* moveDir , ForceMode.Force);
IDE iirc will help you do it
Ohh, I see. That actually makes sense.
Thank you very much, both of you! :)
general question: Is someone doing like mentoring / teaching about unity stuff?
Basically what I mean is theoretically me hiring a mentor that will help me with solving different problems with my project on request.
That's not a hiring message. I am just curious if something like that exists.
fiverr
oh, thank you. Have to check that resource
it makes game
perhaps look at the documentation ?
https://docs.unity3d.com/ScriptReference/MonoBehaviour.html
It gives you access to properties and methods from that class and the ones it inherits from.
Standard OOP
It's like your little custom component.
What does inherit mean exactly in coding context
You should definitely look that up
It is a very basic concept in coding. It is a foundation of Object Oriented Programming
You might want to take this basic c# course. It is very good and goes over inheritance
https://www.w3schools.com/cs/index.php
Hey there! I am trying to use the Rewired API to take in inputs from a Logitech G290 steering wheel and cannot get the steering wheel to cooperate. Any suggestions or better place to get info? Thank you so much!
Do mesh collider vs box collider performance matter if nothing is colliding with the objects? If I spawn 1000 objs that really wont collide with anything
mesh requires more operations to check collision, and it's concurrent so it doesnt matter if it's not colliding
I have ~ 4k terrain trees on map. I want save info about each of them (position, rotation etc), then remove and Instantiate prefabs on their position - any advice to performance?
trying to set some default values for some variables within the script in case i forget to manually adjust the values in the inspector. for some reason if i have leftLimit declared first, the default value for rightLimit set via script seems to be ignored in the editor, but if i declare rightLimit first, it seems to be fine. why is this so?
how are you testing default values; because unless there's an extreme bug I doubt this is actually happening
You could just try loading them in and disabling them until you decide you want to render them. I think they are still statically batched in this regard, otherwise you'd have to dynamically batch them if you choose to load them later on at runtime.
well i'm just doing this. i want to horizontally clamp camera movement (i've done that later in the script)
Are you resetting the component via the context menu to see the default values in the inspector?
oh that works thanks. not sure why rightLimit was going to zero when declared second though
(also those are some bizarre magic numbers to use for defaults)
well, the decimals specifically is so i can have the walls snug against the sides of the screen
the 999 part of rightLimit is just some arbitrary large number that probably won't be reached
There are better ways to do this
i'm sure there are, but this is working and simple enough
Hey,
Quick question. I am making a Player Controller script based on Rigidbody.
If I want to rotate the Player, can I use the transform.Rotate() method or should I use a Rigidbody based rotation, such as Rigidbody.MoveRotation?
You should use rigidbody based rotation.
Perfect. Thanks!
Is it worth it to restart the script for player movement if the code is messy and only works 95% of the time.
refactoring is important sure
Okay thank you
get => _Health;
private set {
if (value < _Health)
{
if (UIContainer.enabled != true)
{
UIContainer.GetComponent<Canvas>().enabled = true;
StartCoroutine(Wait(3));
UIContainer.GetComponent<Canvas>().enabled = false;
}
}
_Health = value;
}
}```I am trying to make a health bar appear when an object is damaged. No errors but the canvas is not being enabled
I don't know why I get this mistake if you can help me, making the text big when you enter and get little when you already enter the screen but this comes out
You enable it, start a coroutine, then disable it all in one frame
A coroutine only makes the code INSIDE it wait, nothing else
You have LeanTween imported?
Never used it, but are you sure that is the Namespace you need?
Don't use notepad++ to program.
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Oh god, how did I not notice that?!
No idea, you should have noticed their error was not underlined at least 😛
Definitely haha. Dangers of multitasking
Is the access to Animator, Vector2 and Rigidbody2D aggregation, composition or neither?
Is this a test 🤔
Yes, maybe? idk, I just need to figure this out
whyare you using notepad++ lmao
Figure this out ... for a test?
No It's not for a test
So are they composition, aggregation or neither. I'm trying to figure this out.
It is the only one that goes fast the visual studio 2017 sees slow and says that it does not respond
even 2017 is outdated as hel..use 2022 VS
2022 is faster cause its a 64x bit application
Should I ask this in the general or advanced or something, I need to figure this out by saturday.
I will be able to use the unity and the visual Studio 2022 well when my improved new laptop arrives
Well there are the mistakes that come out
Why would you need to figure out something so banal if it wasn't for a test?
Because I have coursework due on the 15th and my plan includes finishing this part by the 6th.
This part includes figuring out if these three variables are aggregation, composition or neither so I can change the title and/or remove it before I begin typing it out. (As I can't talk about aggregation if it's composition)
and the package is installed?
btw DOTween highly superior Imo
maybe I shouldn't have been specific and just asked if it was for homework; because it's obnoxious as hell to be asked multiple-choice questions
So... any clue on the answer?
have you considered reviewing your course materials to find the answer?
What pack of unity?
I have, I know what aggregation and composition is but the actual application in figuring out if something is or isn't either is confusing.
I mean I guess aggregation is dependancy so I'll just call it that and stop flooding chat, gracias.
these are nitpicky OOP buzzwords. very annoying to think about
the package ur attempting to use
But what package?
it's a mystery
Unity comes pre-packaged with many things..
like these two...
NaughtAttributes is not default
i'd have to install that
I just put the unity package and now
GPT code 💯
look at this.. its in the Unity Asset Store..
if u check the Documents it shows all these parameter's and functions each one is following a LeanTween.
thats what the using LeanTween means..
it means when u call any of these. it knows where to look.. until you install it.. it doesn't exist
and yes.. DOTween is better IMO.. and it has pretty much identical features
tell me how I should be here?
It's just suggesting that you use those two newer methods.
The old one will continue working (for now, at least)
SoundManager sounds like a fine thing to make a Singleton with a static accessor though, negating the need for a Find call
SamuraiButton = GameObject.Find("SamuraiButton").GetComponent<Button>();
KnightButton = GameObject.Find("KnightButton").GetComponent<Button>();
WizardButton = GameObject.Find("WizardButton").GetComponent<Button>();
ButterButton = GameObject.Find("ButterButton").GetComponent<Button>();
why doesnt this work they never get assigned to stuff
check your console for errors
when I create a singleton in it, for some reason the music stops playing
this should relate to code , sorta UI design
my team is using a pretty bad UI deisgn rn, basically we call and stack UI one by one, so in order to make thing less chaotic, we will put a panel for the top UI
What do you mean "in" it?
so it will hide other UI under it
but now every UI is calling a panel, too many panel stacking is not good
is there a way , to allow only one panel exists, but that panel can always under 1 level of the top UI
for example
@summer stump
UI 1 top
panel
UI 2 bottom
UI 1
panel
UI 2
UI 3
without calling gameobject.findbytype
or get componentbychild
You're adding an AudioSource component for every sound you have on one GameObject, why?
soundManager.PlayClip("Backpack close");```
and that's how I add where I need to
I understand the array of Sound, but why add an AudioSource component for every single sound? Say you have 100 sounds; youre adding 100 AudioSource components to the sound manager GameObject . . .
I generally do the reverse:
public static SoundManager Instance { get; private set; }
void Awake()
{
if (Instance != null)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
But that should be fine.
Is it getting destroyed though?
Also note that the static variable (where you put the //singleton comment) is not the singleton, the class is. A singleton doesn't even necessarily need the static accessor
You can replace the properties of an AudioSource with the fields from the Sound instance before playing the clip . . .
Does dependency injection mean using serialize to add the reference to a script?
that is a basic form of dependency injection, but is not the only form of dependency injection
do you know a place I can see the diffrent ones
it's a very broad concept
it's really just when you give something another object, instead of that thing having to create its own object
dependency injection is just the concept of injecting a dependency into an object. this can be done any number of ways. you can do so by simply assigning a reference via the inspector, pass a reference to an object via method parameter or directly assigning to a property/field, use a full on dependency injection framework, etc
if you want to give yourself a heart attack, look at the readme for Zenject
ok thank you
Oh dear, not Zenject . . .
I took it from some kind of lesson
you have written a local function called Awake and stuffed it into your Awake method
sorry, Thanks, I didn't even notice.
I was trying to make some kind of general sound manager for each object so that I could then turn down the sound for all of them with one slider
You should look at sound mixers.
You can route all of your audio sources into a mixer and then control its volume
Now I can't find the sound, as it was before
everything works fine with this
but don't you need such managers?
maybe there is some great video? So that I can get rid of him
i mean you don't need a sound manager. especially not to just easily control the volume of a group of different sounds
I just don't understand where to store the sounds.
Do that in Start. Instance is set on Awake, so you're grabbing the reference too early
although apparently audio mixers don't work in webgl so that's a consideration
how do they do it in large expandable projects?
do what? because it seems like we are referring to different things
aeugh
I don't have a webgl.
okay, thx
then that concern is not relevant and you can use audio mixers all you want
yes, nice work, ty bro
Use audio mixers, for sure. You place a reference to an audio mixer inside of an AudioSource component. Any AudioSource linked to that mixer will use its settings . . .
this is why i use the secret __internalAwake for my singletons
I'm sorry, of course, but as a beginner, can you tell me if I need this sound manager?
as they usually do in large projects so that I can expand it later without rewriting the code
I just now noticed that it creates 5 audio tracks
even opening the inventory, although I didn't use it
wdym it creates 5 audio tracks? or are you referring to the 5 different AudioSource components? because that has been the concern everyone else has been pointing out this entire time
no, I didn't point it out as a problem, I didn't even notice it, someone wrote to me in a chat about it why do you need so many tracks
I decided to check if it was true.
that's the whole point of this entire conversation. have you just not been paying attention?
This is what I mentioned earlier. Your code adds an AudioSource component to the GameObject for every Sound in your array . . .
the point of the conversation was that I couldn't find a replacement for findtupe in the new version of unity, I tried singleton but it gave me an error
maybe it was you, I didn't remember the nickname who told me about it.
i'm referring to everything after that part. you know, where everyone is trying to find out why you need a different AudioSource for each sound clip and the entire point of the soundmanager in general
You only need an AudioSource for each type of sound, like: background music, sound effects, dialogue, and UI . . .
could you tell me how to do it better, because I will have flexible sound settings for each, such as music, sounds, environment and UI
does anybody know why this while look crashes my unity?
because its condition never changes
1 / cooldown * elapsed <= 1
this?
I thought it was convenient to just add this to the code soundManager.PlayClip("Backpack close");
yes. you probably don't even want that to be a while loop, unless you want to change this to a coroutine with a yield return null inside the loop
this is anti-good. you're using a string to play a clip. if you change the name of the sound clip, all of your existing code breaks
I didn't understand you a bit, what do you mean
I am working on a reasonably sized game that's been pleasant to develop so far. Perhaps you'll be interested in how I'm handling sound in it
yes, because of this, there was a check
what should it look like then?
I have an AudioSource on each "thing" that can produce sounds. Each thing will either directly reference AudioClips or reference another asset that holds AudioClips.
Of course bro I'm interested
Each AudioSource has a sound mixer set on it to route the sound to the correct category
I'm always glad if someone shares their cool experience.
either not a while loop and simply just an if statement and you call the method every single frame or make that method a coroutine like i suggested
Ambient/Speech/SFX/Music/etc.
I sometimes have multiple audio sources. I do this if I need continuously-playing sounds
could you show a screenshot of how it looks on the object
ok I'll try it out, thanks
e.g. a computer has a looping fan noise and also randomly plays beeping sounds
that'd be two audio sources
There's nothing really special here. I just have an AudioSource on the same object as the component that wants to play audio.
The game also has a hand-rolled spatial audio system that tries to add reverb and adjust the position of audio to sound more realistic...but that's out of scope 😉
look, for example, I have an inventory, how do I put two closing and opening sounds on it?
Give the inventory component AudioClip fields for the opening and closing sounds
wait actually I don't understand, how does this condition never change?
and give it an AudioSource component that it references
1 / cooldown * elapsed <= 1
```this line shouldnt freeze your unity btw since the elapsed is incremented by time.deltaTime, the only reason casuse the line of code always false is 1/cooldown=0 (cooldown=infinity ?)
btw 1/infinity will not give you segfault and crash your unity
it's a while loop without a yield in it
[SerializeField] AudioClip closeClip;
[SerializeField] AudioClip openClip;
{SerializeField] AudioSource audioSource;
whatever it does it will execute instantaneously. You have to ask why it's a while loop in the first place
okay, thx
cooldown = 0.7 in my inspector though
Use the method that Fen is using. That's exactly how I've set my up before (minus the cool hand-rolled spatial stuff) . . . 😔
The loop shouldn't freeze Unity forever.
It will just execute all of its iterations instantly
If Timescale is 0
okay, ty
True. Or if it happens in a frame with a deltaTime of zero
I know turning on the recorder causes one of those.
cause I want the code to repeat until the condition is met
Instantly?
Do you want every iteration to run all at once?
ty bro
Thanks guys, I would have sat there and continued to be stupid.
I wish I could just use Steam Audio...
(it does not work on ARM hardware)
how do I make it not run instantly then?
steam audio?
someone has already told you use coroutine
Use an if statement in Update, keep the while loop but use a yield in a coroutine, or await in an async function
i'd be interested in hearing more about that spatialization. i've been testing out steam audio but i cannot for the life of me get it to actually sound good, but i'm also not very smart when it comes to audio stuff 🤷♂️
I'm approximating how sound travels using a nav mesh surface
I calculate a path from the source to the listener and compare its length to the straight-line distance
I also count how many corners the path has and how sharp they are
Ok ill try it out, thanks for the help
That's used to compute a "directness" value
Low directness causes the audio source to get a strong reverb and low-pass filter applied to it
I also shoot a raycast and cut the directness if it hits a wall
That is SO SMART! I love it
I measure paths from a few different positions to help blend it better as well
The more difficult thing I then do is actually reposition the audio source
I still need to work on that logic. I forget exactly what I did, actually...not at my laptop right now
I think it does a weighed average of the path points and slaps the audio source there
Keep in mind even if you call flap() every frame, because you have while loop inside, it's going to infinitely loop after first frame, so the next frame will never come because it's infinitely looping inside your while
Tbh never mind, I am confused by this code because I don't see where flap() is being called
heavily weighing the points closer to the player
I originally wanted to compute a graph of 3D volumes (so, box colliders) and do A* to navigate from the source to the listener
I might try that again, but having unity make the navmesh and do the pathfinding for me is pretty nice...
I can see doing that in order to get a direct"ness" value. That's where I got lost because I didn't know how to handle altering the sound based on that value . . .
Try finding a loud, noisy thing that's got some obstacles around it
like, in real life 😨
listen to how the sound changes as you walk behind obstacles
you'll get a low pass filter (high pitched sounds go away)
fountains are a good source of noise. i notice the effect when i walk past a wall
Then you mix in reverb. The more indirect the path, the more reverb you want to mix in
more wet, less dry
wet = the result of the reverb filter, dry = the original audio
high frequency (low period) signal not easily bend?
completely forgot the physics term
Any consideration for surface hardness in your system?
No, I'm not considering that at all. I guess I partially account for that with audio reverb zones
I'm not doing a lot of clever stuff that Steam Audio is
They attenuate more strongly on reflections, while low-end frequencies retain more of their power. So it's not about the spread (or bend as you say), but the build up of reverberation and possible standing waves (which are less likely in high frequencies due to their wavelength being so small).
So in essence, the direct sound is blocked. The early reflections contain less high end, the reverberant sound is going to contain WAY less high end.
would zenject be a good idea to learn or is it better to just used unity's serialize
do you need an entire DI framework?
Say I had 14 days to create a game. would it be worth to learn it. I dont know if I need on ever not seen Ive never used one
don't just go adding a giant complex framework to your project if you cannot currently see why you would need such a thing
I have never touched Zenject and I've never really felt the burning desire for it
ok i wont use it
make your game.
Two weeks? Forget Zenject even exists. Just drag and drop . . .
ok
can i modify gameobject hierachy under certain gameobject
like this
A
obj1
obj2
obj3
and then make it like this
A
obj2
obj1
obj3
In code you mean?
Sure, you can set the sibling index(was it) of a transform.
Look at the Transform docs. It's responsible for placement in the hierarchy.
so my team has implemented a very bad UI design , which is common in every dev team in my city
we basically make a parent UI canvas , and then put every single UI we need under it, and we not even doing any sorting layers to any UI
it has, its just all UI are put under same big canvas u know
the way my team call the UI is , call A => call B => call C... so UI will keep stacking
my task now, is to put a panel mask on the top UI, the most "surface one"
so , in order for me to do that, without sorting layers, and a script to store all UIs called, i will need to find every UI i need , and then put the mask under it
It's not that bad.
This sounds fine.
this is not bad
way better than previous team
aight lemme try it
but u cant do sorting layers as the whole UI is almost finished, and they all rely on current structure and without sorting layers
u need to add another canvas on those sub UIs under the canvas right? in order to use sorting layers
Yeah, I guess so. Though, you don't have to use sorting layers.
Or you could probably add canvases without it affecting stuff.
not necessary, but it will be better to have i guess
Hey Guys, if I want to make a player do an animation when taking damage, Is it better to do things:
A) from the damage script(Enemy Script that handles collision damage) and set a flag on the PlayerController to deal with animation changes
B) Somehow do this directly on PlayerController
C) Other way
make the enemy script tell the Player that it is dealing damage. then the player will do whatever it needs to in reaction to that. don't make your enemy control your player
So A, idk if I worded it right but thats basically what I first had in mind
How would you handle this in your player script? As of now Im just thinking of a variable that when true, triggers the animation in the animator, but Im curious if theres a better way
well it sounds like with A you are making your Enemy object tell the player that it should animate. but that shouldn't be the case. the Enemy should only care about dealing damage. So create a method on the player that receives damage and have the enemy call that method. Then the player can do whatever it needs to from that method
Yeah, I worded that weird, the enemy collision script just triggers a TakeDamage(value) right now
that's really all the enemy should be doing. so then your TakeDamage method can notify your animator (or some other component on your player that controls your animator if that's how you have it set up) that it needs to do the damage animation
Can anyone help me with being able to zoom with the mouse in my camcontroller?
I just got here and read a bit of the read me, but I'm still confused on if we post questions here or if there is another channel
if it is coding related, here is fine. otherwise #🔎┃find-a-channel
Right now I actually have all my health stuff in a separate script from the player. IDK if this is good practice or not. So I dont know if I should just merge that to my player controller or just have the TakeDamage call a method in Player controller
the latter probably
Thanks a lot boxfriend
or slap an event on it that the player controller subscribes to
I think this should be something along the lines of finding the camera game object and implementing a scroll wheel system to give off a float variable. Then you'd set it equal to the variable you made the camera size
Damn
Sorry, you're right. I already have some initial code, I don't know if it's right but I want to change it in a way that actually works haha
then you should share the !code and explain what isn't currently working about it
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Okay, thanks. I'll delete my message here then?
yeah, you're technically supposed to when you move a question to another channel to avoid being moderated for crossposting
Cool, thanks friend 
What are the odds of anyone answering my question there though, it seems kind of quiet
nvm, probably in the morning lol
at this point you should just use a paste site @queen adder
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
these protected fields are so tempting to inherit from 🤤
Anyone ever inherited contentsizefitter to implement their weird thingies?
where the 'if' statement starts is where the scrollwheel is meant to work.
you probably want to change the transform.localPosition rather than the transform.position
but also i recommend swapping to cinemachine for camera controls. and also not making your camera a child of the player
ok, thank you!
Anyone know why I might be getting the wrong mouse position when I try to drag? Like to drag the first slot I have to be like 100pixels to the left of it to pick it up?
public void OnDrag(PointerEventData eventData)
{
// Convert event position to canvas space
Vector2 position;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
canvas.transform as RectTransform,
eventData.position,
canvas.worldCamera,
out position
);
3rd image is from a second class, if I have a debug.log in the first class and I click on a button placeMode = [the correct mode] and CurrentMode when called from that class outputs [the correct mode] but when I call CurrentMode from another class and I debug.log(mode it outputs "none"
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/enum
no quite related to your problem but i think you need it
I know what enums are how does that relate to static classes?
you can put enum where ever you like
so just make placeMode an enum and it works you say?
yes, since you wont mistype room to Room (or vice verse)
simply changing to an enum instead of a string won't fix the issue you've described, but it is still a good idea
your issue is also likely due to the order you do things in or other objects changing the value of your static variable. since anything can access it and change it at any time, you need to examine all locations that are accessing it. you also need to make sure you are assigning to it before you try logging it
yeah just enumified it, this is the only location that accessed it
and it is only modified in the SelectPlacement function
if you are certain that the two locations you have shown that access and modify that variable are the only locations that do so, then the issue is the order your code is running
btw having public static is not good idea as boxfriend said since everything can change it
what should I do to make it so only that function can set it but any other function can read it's value
you probably want the variable to be private
i think control accessibility down to method level is impossible in c#
so be carefully
true but then other classes can not read it
you're exposing it through the method that is declared directly below it. read it from that
If you want something public, make it returnable by a method, or at least make it a private set property
if you want other class can read but not wirte it
It turns out it wasn't a code issue
I hadn't pressed the button when testing to change the mode
it was a failure of UI all along
I really should add some visual cue that the button is/isn't pressed
alrighy I'm confused
put it inside of a method
debug has to be in a method?
any expression that is not a member or type declaration has to be
in hindsight that seems extremely obvious
I've apparently never tried to use a debug statement outside of a method
why does OnTriggerEnter only happen when a rigidbody accelerates towards my game object
here's how you can troubleshoot OnTriggerEnter: https://unity.huh.how/physics-messages
what would be the best way to detect if my player touches another game object?
for example, like the crash nitro boxes that instantly kill you when you touch them
well the easiest would be OnTriggerEnter or OnCollisionEnter or if you are using a CharacterController then OnCharacterColliderHit or whatever its special collision message is
that only works when
the player explicitly moves towards the object (character collider hit)
or
the object explicitly moves towards the player (trigger/collision enter)
right?
what?
if you are referring to the CharacterController's collision message, then yes. that only occurs when the CC performs a Move. the other two do not rely on that
seems like we would need to use both
OnTriggerEnter to detect an object pushing against us
OnControllerColliderHit to detect us pushing against an object (standing on top counts due to gravity i assume)
but im not sure how to detect contact with an object that is not pushing against us nor that we are not pushing against
well trigger colliders, which are required for OnTriggerEnter do not physically collide so there is no "pushing against us" there. and you would use that or OnTriggerStay to detect overlaps with trigger colliders.
otherwise colliders that are moving that are not triggers will need their own rigidbodies to produce OnCollisionEnter messages, which will be sent to the CharacterController. the CC just doesn't produce OnCollsion messages on its own
yea
what if both objects have a rigidbody
eg, detect a game object resting against another game object
charactercontroller and rigidbody do not mix
but what you've described would be covered by OnCollisionStay. you should consider reading the documentation, you'd figure this stuff out easier
they do if we use a kinematic rigidbody that does not use gravity
and yet you still don't need a rigidbody on a CharacterController. as long as the other object has a rigidbody it will send an OnCollision message to the CC
hmm it doesnt seem to trigger OnCollisionEnter
show both objects
naturally a trigger collider does not produce a collision message because as we've established they don't collide
but also two kinematic bodies coming in contact with each other also do not produce a collision message
hmm Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached
should i just assume unity cannot do this level of precise interaction
what "level of precise interaction" are you unable to achieve?
if collision messages aren't working for you because you refuse to set up your objects in a way that would allow them to work (you should really just be using OnTriggerEnter/Stay at this point considering you want to use kinematic rigidbodies anyway) then just use physics queries and check it manually
this
great! now read the rest of my message
would i do var col = Physics.CheckCapsule(_controller.height, _controller.height + _controller.radius + _controller.radius, _controller.radius);
Basic question: If I instantiate a GameObject in runtime and that prefab has a script attached to it. How can I access that script?
instead of using a GameObject reference for the prefab variable, refer to the component directly. then Instantiate will return a reference to the instantiated instance of that component
GetComponent on the instantiated GameObject
"go.GetComponent<Agent>().layerGoal = goalLayer[i];"
Like this? Didn't work, says it can't find layerGoal, but its just a basic public int in Agent.cs
go is the instantiated object
show the Agent class and share the actual error message
Its as basic as it gets
public class Agent : MonoBehaviour
{
// Start is called before the first frame update
private int layerGoal;
void Start()
{
}
public void setLayerGoal(int t){
layerGoal = t;
}
// Update is called once per frame
void Update()
{
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.layer == layerGoal){
}
}
}
I just changed it to try and use a function to set it instead and change the variable to private
Still same issue
now show the line of code producing the error
GameObject go = GameObject.Instantiate(prefab, spawnPosition, Quaternion.identity) as GameObject;
go.GetComponent<Agent>().setLayerGoal = goalLayer[i];
there you go. setLayerGoal is a method not a variable
also make sure that your !IDE is configured to help prevent these basic syntax errors
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Does anybody know how I might be able to the the rate of change at a point of an animation curve?
i mean like I said above I did try as a variable first, by directly accessing layerGoal (and it was public then)
This was just a change to try and use a method instead to see if it would work
Same issue
GameObject go = GameObject.Instantiate(prefab, spawnPosition, Quaternion.identity) as GameObject;
go.GetComponent<Agent>().setLayerGoal(goalLayer[i]);
you're probably using the wrong Agent type then
hover over the type Agent on that line and make sure it shows the correct type
that's irrelevant. prefab names are not types
I mean it works now, changed the scriptname to AgentController
then you were using the wrong agent type
Strange, oh well it works, ty
void Update() {
if (cached_character_controller != null && Physics.CheckCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius)) {
if (!ragdoll_was_forced && canRagdoll && !in_ragdoll) {
ragdoll_ms_remaining = ragdoll_duration_ms;
turn_ragdoll_on();
}
would this do?
oof i instantly ragdoll
use a layermask for your CheckCapsule
otherwise it's likely going to find its own collider
still though, i don't see why you don't just use OnTriggerEnter or OnTriggerStay if all you care about is coming in contact with another collider
how tf is a bool considered a and returns detailed information on what was hit.
where are you seeing that at
OverlapCapsule seems to be better
https://docs.unity3d.com/ScriptReference/Physics.CapsuleCast.html
Returns
bool True when the capsule sweep intersects any collider, otherwise false.
Description
Casts a capsule against all colliders in the Scene and returns detailed information on what was hit.
that's not even the method you are using
and anyway, it populates an out parameter of type RaycastHit for that info
would OverlapCapsule be less expensive than CapsuleCast
you can use the profiler if you have concerns about performance
but they aren't really substitutes for one another. one checks if anything is within the capsule's area. the other casts the capsule in a direction. if you do not need to move the capsule for the query, then you do not need capsulecast and can just use overlapcapsule. if you do not need any of the info about what was hit then you can go back to using checkcapsule. no matter which of these you use though you will have to use a layermask
imma assume an overlap check is less computational than a raycast
CapsuleCast has a direction
oof
var cols = Physics.OverlapCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius);
foreach(Collider cs in cols) {
if (cs.gameObject == cached_character_controller.gameObject) {
continue;
}
bool collider_is_ragdoll = false;
foreach(Collider c in ragdoll_colliders) {
if (c.gameObject == cs.gameObject) {
collider_is_ragdoll = true;
break;
}
}
if (!collider_is_ragdoll) {
if (!ragdoll_was_forced && canRagdoll && !in_ragdoll) {
Debug.Log("overlap: " + cs.gameObject);
Ragdoll(cs);
}
}
}
this doesnt trigger at all x.x
start debugging
i already know its cus every collider returned is one that is the pleyer itself or inside the player
good thing though is you don't have to deal with trigger method bs this way
otherwise it should have ragdolled
Use a layermask
all layers are Default
So change them on either the player or whatever type of object you are trying to detect
can you guys help me with my issue #archived-code-general if you may
By avoiding a layermask and swapping to overlap capsule from CheckCapsule you've started creating way more garbage (especially since you aren't using a nonalloc version)
Don't crosspost
ok
oof error CS1061: 'Collider[]' does not contain a definition for 'toList' and no accessible extension method 'toList' accepting a first argument of type 'Collider[]' could be found (are you missing a using directive or an assembly reference?)
var cols = Physics.OverlapCapsule(cached_character_controller.center, cached_character_controller.center, cached_character_controller.radius);
frame_colliders = cols.toList();
frame_colliders_game_objects = frame_colliders.ConvertAll(new Converter<Collider, GameObject>(c -> c.gameObject));
Spell it right
'Collider[]' does not contain a definition for 'ToList' -_-
Now use the quick actions in your configured !IDE to add the relevant using directive
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Well having a configured IDE is required to get help here so if you don't want to deal with whatever vs code is doing you can switch to a real IDE 🤷♂️
how long have you been here that you're posting pics from your phone
lol im at work
i cant download discord on my working pc
i dont use laptop, so either phone or working pc in my workplace
shouldnt this be at least detecting ANY colliders?
Collider[] cols = Physics.OverlapCapsule(capsule_center, capsule_center, capsule_radius);
this should detect at least one collider, right?
or would start == end yield a 0 distance overlap check regardless of the radius and thus optimize for
if (distance == 0)
return empty;
maybe Collider[] cols = Physics.OverlapCapsule(transform.position, transform.position + new Vector3(0, cached_character_controller.height, 0), cached_character_controller.radius);
welp it detects the ground
but doesnt seem to detect the cube unless we actually stand on top of it
welp imma just ignore for now
its good enough, doesnt have to be perfect
how do i get my character to move with my ragdoll instead of freezing in place until it respawns
eg
additionally how do i get a timer to be timescale dependent?
if (old_fps != 60) {
old_fps = 60;
ms_per_frame = (int) (1000.0f / 60);
}
if (ragdoll_ms_remaining >= ms_per_frame) {
ragdoll_ms_remaining -= ms_per_frame;
} else {
ragdoll_ms_remaining = 0;
}
if (ragdoll_ms_remaining == 0) {
turn_ragdoll_off();
}
i finally found the place that states time.deltatime is affected by timescale
read the "Time Scale" section
like, i would do 1000.0f / 60 / cached_third_person_controller.world_current_scale right?
where is the 60 comes from?
or rather
(1000.0f / 60 / cached_third_person_controller.world_current_scale) * cached_third_person_controller.player_current_scale
to also account for the player time scale in relation to the world scale ?
60 is the assumed target fps
as i currently use targetFrameRate for simulating heavy load
then how you know your machine is actually running your game on 60fps?
btw get the deltatime first then further manipulate it
can I invoke repeating in start with a delay like a coroutine?
or does invoke repeating always call the method every single second with nothing you can do about it?
i use 60 as an assumed target fps, later this would be changed to a game option to toggle between different target frame rates
not sure tho
since targetFrameRate affects how often Update is called and how much render time we get
(eg, 120 fps on a 120 hz monitor)
as i said what if your machine not running your game in your targeted framerate...
eg if the cpu is busy
i guess i should rename it to
int target_FPS; // affects render + timers
int simulated_target_FPS; // affects render only
is there a way to check a compare tag but only every so often?
what’s the input.getaxis axis for the keys A,D and W,S?
The keys relative to the axis are defined in the Input settings which you can edit in the Project Settings -> Input Manager
by default the axises for the movement are Horizontal (A, D) and Vertical (W, S)
aren’t the arrow keys?
they also are arrow keys
You can add alternative buttons
ok ty
https://hatebin.com/mibhdmhdab
this is giving the player a constant speed towards the sky even when spacebar is not pressed
of course it is, your code makes no sense
what do you think this
if (Input.GetKeyUp(KeyCode.Space))
{
jumpForce = 10f;
jumpForce = 0f;
}
does?
it adds a force only once
no it does not
bc otherwise it would give a constant speed on the Y
do i need to put the second jumpforce thing outside of the if condition?
youre assigning it a value of 10f and then setting it to 0f on the same frame so at the end its the same as just doing jumpForce = 0f;
it sets a variable to 10 then immediately back to 0, nothing more
so i need to set it to 0 at the start of the update method?
how would that help?
this way it will add a 10f force to the rigidbody in that frame, and the next will have an 0f force
you are not even adding force you are just setting velocity
you need to "apply the force" when the key is pressed instead of applying it anyway
velocity is a force
not in this context it is not
i just modify it if the key is pressed
velocity is a vector just as much as the acceleration
can't i modify the velocity if the key is pressed?
yes thats what you need to do but currently you're modifying the velocity regardless of if the key is pressed or not
i know i can just use rb.addforce but i wanted to try other things
you dont need to use rb.addforce if you're going for a certain type of movement
velocity is the result of force not a force in itself
but it adds 10f only if the key is pressed, i don't get it
Rigidbody.velocity = new Vector3(horizontalInput, jumpForce, 0);
you're constantly applying the jumpForce here
what would be better is to only apply the jumpForce when the key is pressed
but it's set to be 0f at the start of the script
could do += instead of =
yea and it remains at 0 anyway because you set it to 10f and 0f on the same frame
why does 16.66667f / 0.999999f result in zero ?
can someone help make 2d top down car which player can handle like in old GTA games
i am making a open world survival 2d topdown game in unity 2d
can someone help
ok
a better way would be to ```cs
Rigidbody.velocity = new Vector3(horizontalInput, 0, 0);
if (space)
{
Rigidbody.velocity += new Vector3(0, jumpForce, 0);
}
but then how do i set it back to 0?
dont need to
just keep it at 10f
whenever space is pressed, it should set velocity.y to 10f for 1 frame and then let physics do its thing
but this way the speed on the Yaxis remains 10 after the key is pressed
physics should reduce the speed automatically unless you have gravity disabled
oh actually there's gonna be a small issue lol
it's gonna reset velocity.y to 0 the next frame so its gonna be buggy. The way to fix it would be to not change the velocity.y at all when space is not pressed```cs
Rigidbody.velocity = new Vector3(horizontalInput, Rigidbody.velocity.y, 0);
if (Input.GetKeyUp(KeyCode.Space))
{
Rigidbody.velocity += new Vector3(0, jumpForce, 0);
}
okk ty
https://hatebin.com/wdonduqods
is this fine then?
is this a 3D game btw?
wondering why z velocity is always 0
oh i see
but it's my first game
yea that code should be fine
kind of a copy of another platform game
i hadn't other ideas about any other kind of game
oh hold on
i need to multiply the horizontalinput for the value of the force i want to add for time.deltatime
right?
yea multiplying horizontalInput by time.deltatime is better since it should make the movement in your game not be dependant on frame rate
actually it shouldnt matter if you use time.deltatime on it or not since you're setting it to a constant velocity
oof i was forgetting to set cached_third_person_controller to an instance
https://hatebin.com/wtwpepkisj
it's not working for the horizontalInput
remove Time.deltaTime, and you can make the 100 into a variable called speed and modify it in inspector to see what speed suits your liking
okk
tried, now it works, thanks @dire torrent
I dont really know how to fix this issues and it has always happens to me before but when i try to add an new feature all the other ones stop working and only the new one does, here is the code:
Cameraposition = GameObject.Find("Main Camera").GetComponent<Transform>().position;
is this a good way to make the camera follow the player? instead of using another script, just finding it and using its transform?
currently only the crawling works but the crouching and sprint dont
- what is this script on?
- Dont use Find methods. They're unnecessarily expensive and very easy to replace.
- you can store a reference to the camera by making it visible in the unity inspector and assign it by dragging the camera onto the field in inspector.
1 it is on the player script
2 i did bc the learn.unity tutorial used it a lot
3 so i need to use public Camera mainCamera?
the flow of your code is off. look at how the control goes. go through it line by line
this is how its working rn
if shift is pressed
you set the speed to 18f
then if leftcontrol is not pressed
you set speed back to 12f
then if C is not pressed
you set sped to 12f
so in the end the only thing affecting your speed is whether you are holding down C or not.
it is best to control the camera by putting a script on the camera itself. Something like CameraController.
its a good way to structure your code so you know that only the script on the camera is affecting the camera. not other scripts.
hm, thanks for explaining but i dont really understand how to fix it
okk
do you understand why it's doing what it's doing though?
but then i still need to find the player gameobject to attach the camera to it
yea you would make a reference to it by using something like public Transform playerPosition
yeah, but that problem has happend sooo many time and i never really knew how to fix it
you need to use if-elseif-else structure for what you're trying to do
https://hatebin.com/optaqwqqdf
like this?
i did bc the learn.unity tutorial used it a lot
also forgot to reply about this, Find methods are a big beginner bait. It sounds really easy to just get the object you want by its name but there's lots of issues to this. What if you changed the name of the object at some point, you would have to go everywhere in your code where you referenced it by name and replace it. And find methods are very expensive too... If you have a whole bunch of objects in your scene, its gonna take longer for the Find method to get the object which is gonna make your game slower the bigger it gets.
so using a reference is just both easier and less expensive, gotcha
this script is on the camera?
yup
so you're assigning playerTransform the value of gameObject.GetComponent<Transform>(). So it assigns the transform of the camera itself
hi can someone tell me why the planes gameobject on my ""tree"" have such a weird behaviour?
just assign it through the inspector, and remove the line in Start
i assigned the player gameobject in the inspector
and with that code it works
no, wait it does not
yea it shouldnt because in Start you assign playerTransform back to the camera's transform itself
ok, i used playerTransform.GameObject.GetComponent<Transform>(); and it works
why though if you're already assigning it through inspector lol
playerTransform already has the value through the inspector. Assigning it again in Start wont do anything except maybe extra redundant calls
oh ok
transform.position = playerTransform.position + cameraOffset;
so i need just this line, right?
yes
ty dude for being patient
also, if something is private, does it mean it's less expensive?
no but its better to make things private that arent being referenced from another script/class
good thing you ask because if your only purpose to make something public is to expose it to unity's inspector, you can use [SerializeField] instead.
so something like ```cs
[SerializeField] private Transform playerTransform;
what's "serializefield"?
but if the only purpose to make something public is to show it in the inspector, what's the point of making something show while making it private
well, i dont realy know how to do it with the if-elseif-else
because its confusing