#đ»âcode-beginner
1 messages · Page 126 of 1
Mouse/touch/pointer interactions with UI (And non UI) objects
So it should not be used for linking things like button clicks to events that other objects listen to?
The event system facilitates the button click handling itself
Do you have a link to a good tutorial by any chance? I tried searching on YouTube and they all seemingly were using their own custom event systems
A good tutorial for what exactly? What specifically are you trying to do?
So basically, I'm making a card game. I have a button that when pressed, toggles the deck view on/off.
Ok and what problem are you having with it?
Right now I'm using a custom "EventManager" object that has this script attached.
!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.
Ah thank you.
So this is the script:
https://gdl.space/oditaqasem.cs
Then on the button in the inspector, I have this
And then this is my "BattleUI" script: https://gdl.space/sibuwikihi.cs
The only issue I see so far is that your DDOL singleton event manager button onclick setup is going to break when the scene changes.
So right now, this works if the "BattleScene" is the first scene to be loaded. However, if I transition to it from another scene, it doesn't work
Yeah this exactly my issue
yeah basically this screenshot right here is the wrong approch
instead of linking the button directly to that function in the inspector you should make a script ON the button with this function:
public void WhenTriggerBattleButtonClicked() {
EventManager.current.TriggerBattleDeckButtonClicked();
}```
and link that
this way it will always use the correct EventManager instance
Oh cool, thank you. So just do it programmatically rather than through the inspector?
well you'll still use the inspector
you just need another layer of indirection so that it's using the correct EventManager instance
do you guys have any idea to why the function rb.AddForce isin't adding any force. It has been a weird problem and nothing is making any sense.
{
if(Input.GetKeyUp(KeyCode.A) == true && Input.GetKey(KeyCode.D) == true && rb.velocityX >= walkingSpeed)
{
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(rightDirection * forceForSuddentChangeOfDirection, rb.velocity.y)); //This line and the one above it are not adding any force
}
else if (Input.GetKeyUp(KeyCode.D) == true && Input.GetKey(KeyCode.A) == true && -rb.velocityX >= walkingSpeed)
{
rb.velocity = new Vector2(0, rb.velocity.y);
rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y)); //This one as well is not adding any force
}
}```
Well first off adding the current y velocity as part of the force is defnitely a mistake
second, you're either not adding enough force, or you're overwriting the velocity elsewhere in your code
what do you mean?
rb.AddForce(new Vector2(leftDirection * forceForSuddentChangeOfDirection, rb.velocity.y));
that should definitely be 0
why would you add the current y velocity as a force there
makes no sense
ohhh yea I see what you mean
I have a hunch that that is the case but I don't see how
here Ill send you the code
Oh I see. So I'll keep it the exact same in the inspector, but just add that bit of code to the button's script?
Or will I reference the WhenTriggerBattleButtonClicked in the inspector?
reread my message
#đ»âcode-beginner message
Ah okay awesome, misunderstood but it makes a lot of sense now. Thank you
I am pretty sure that I am overwriting the velocity in my code, but the thing that I don't understand is that the addForce function is suppesed to increase the velocity at a certain point before it goes back to its initial velocity
well at least that is how I understood that function
hello everyone, I'm trying to add a sound effect into my game however the effect plays with like 150ms delay, I did change the project settings to best latency btw. I'm thinking it's maybe caused by this "dead air" before the sound starts. I tried cutting out that part using an audio editor but unity added a bit of it back on import and I can't seem to be able to get rid of it fully. Any suggestions are appreciated
that shouldn't happen. If you properly trimmed that silent part, unity should import the audio file as it is
maybe your program added it, maybe you didn't save the file...
try again and if it doesn't work i'll try to help you
so @wintry quarry, what do you think could the problem be?
If you do this:
int speed = 4;
speed += 1; // this is like add force
speed = 4;
``` what do you think the speed will be at the end of this?
like I said, if you're overwriting velocity, it doesn't matter what forces you add
the only thing AddForce does is change the object's velocity
I see, then how do I go around this problem? because I can't really think of a way do something about it
You'd have to explain what you're trying to do
well, what I want is that when the player makes a suden change of firection, I want to add force to that direction where he has changed
You're talking in terms of forces. Maybe explain in terms of the actual behavior you're trying to achieve
well, there are three functions in the update, there is the recording the horizontal speed, there is the adding the force when studently changing directions and there is the move function, that checks which keys are being pressed to make a certain movement. It also has acceleration functions and decelliration function. At first I was thinking of adding the sudden movemnt function into the move function but it seems a little too hard
I was also thinking of disabling some functions , switching them from one function to another, but idk how to even do that
Don't use the MP3 format
Although, that looks like an Ogg Vorbis file
MP3 requires the file length to be a multiple of some small amount, which can result in dead air before the audio starts
I don't think that's a problem with OGG, though
oh okay thank you
oh right -- "Vorbis" in that screenshot means it's stored by Unity in the Vorbis format
not that the file it came from is using Vorbis
Unity imports whatever audio format you give it and then stores it in another internal format
Hello, I want to implement a lever that can trigger functions of other objects referenced in lever inspector. I just don't know how to reference functions of other objects in inspector, maybe someone could help me with that or suggest another way of doing this?
You'll want to use UnityEvent
you know how Button has that "on click" list in the inspector?
that's a UnityEvent
[SerializeField] UnityEvent onLeverPull; will add a field called "On Lever Pull" that can invoke a method on another component
If you need to pass a value along -- maybe whether the lever is up or down -- consider UnityEvent<bool>
That would be able to call any method that takes a boolean
Thank you very much! Don't know how I missed that feature đ
public List<AudioClip> SamuraiAudio;
this would allow me to make a list of various audio clips right
I would make a function to specifically ChangeWeaponTo(int ID) which handles that
like your UpdateWeapon, but with an argument of the new id
selectedWeapon = Mathf.Abs(selectedWeapon - 1) % weapons.Count;
you want 0 -> weapons.Count-1
then it gives abs(-1)=1%weapons.Count probably 1
i would
just change it to event based, store the current weapon you use, when switch the weapon, disable current weapon and assign new selected weapon to current weapon
you also wonât need to iterate. just go to the one current weapon and turn it off. then go to the new weapon ID and turn it on, and assign the current weapon id
you would need to actually pass in the argument
i might even change the selected weapon int to be a property with a backing field
but yeah the for loop is a little much. Just disabling the old weapon and enabling the new is all you need
this is how I'd do it too
because itâs basically a getter and setter
that being said I feel like what you have should actually work as is
try adding some log statements to see what's going wrong
also donât iterate
e.g. in your loop you can print whether you're activating/deactivating each weapon
weapons[current].gameobject.SetActive(false);
weapons[newID].gameobject.SetActive(true);
current = newID;
Help! How would i check if a Vector3 is to my players right or his left?
in a property, maybe i can help with syntax:
private int CurrentWeapon { get => _currentWeapon; set {
weapons[_currentWeapon].gameobject.SetActive(false);
weapons[value].gameobject.SetActive(true);
_currentWeapon = value;
}}
From the player's perspective? Or from a global coordinate system perspective?
no, from a 3rd person camera
i would use transform.left or something, take a dot product, and see if that dot product is positive or negative
Yeah but like... From the player's perspective, or on absolute terms?
positive = left, negative = right
in absolute terms you just compare the x coordinate of their positions
player
if you want it from the player's perspective then you'd do something like:
Vector3 localPos = player.transform.InverseTransformPoint(theVector3);
bool toTheRight = localPos.x > 0;
bool toTheLeft = localPos.x < 0;```
you have to define a vector for what is the playerâs left. get a vector from player pos to the point. and then dot product.
this gets the position in the player's local coordinate system, and just checks if the x is positive or negative.
Transform also has methods for this stuff, like praetor is showing, but for simple stuff I prefer to do it like this. because those methods confuse me sometimes
how could i use arrays inside different files?
wdym by "inside different files"?
i think he means in other scripts
what are you trying to do with the arrays?
In general cross script communication works the same way, regardless of whether the field or property is an array, an int, a GameObject or anything else.
making a cost var with diff prices in it
Basically it makes no difference if it's an array
You do the same as ever - get a reference to an instance of the other script. Then you can freely interact with all its members through that reference.
so i got this script
script 1
public class Data
{
public BigDouble money;
public BigDouble[] cost;
public BigDouble lvl1;
public Data(){
money = 0;
lvl1 = 0;
cost = new BigDouble[]{10, 20};
}
}```
script 2
public void Textfix()
{
if (data.money < 1000)
{moneyText.text = "Money: " + data.money.ToString("F1");}
if (data.money >= 1000 && data.money < 1000000)
{moneyText.text = "Money: " + (data.money / 1000).ToString("F2") + "k";}
if (data.money >= 1000000 && data.money < 1000000000)
{moneyText.text = "Money: " + (data.money / 1000000).ToString("F2") + "M";}
if (data.money >= 1000000000 && data.money < 1000000000000)
{moneyText.text = "Money: " + (data.money / 1000000000).ToString("F2") + "B";}
if (data.money >= 1000000000000 && data.money < 1000000000000000)
{moneyText.text = "Money: " + (data.money / 1000000000000).ToString("F2") + "T";}
if (data.money > 1000000000000)
{moneyText.text = "Money: " + (data.money / 1000000000000000).ToString("F2") + "q";}
if (data.cost[0] < 1000) ///this one
{cost1Text.text = "Money: " + data.cost[0].ToString("F1");}
}```
and then i get this error
this is the error IndexOutOfRangeException: Index was outside the bounds of the array.
and there reference is set correctly
cost must be an empty array. You'd have to show how you initialized the data variable
public Data data;i have this
do
public Data data = new();
ok and where are you initializing it? That's just a declaration.
right after i create my class
actually, index out of range exception means it is initialized; but the index is too big
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
using System;
using BreakInfinity;
using UnityEngine.U2D.IK;
public class Manager : MonoBehaviour
{
public Data data = new();```
still same error
which line gives index out of range? is it the one with cost[0]?
yes
call Debug.Log(data.cost.Length);
show inspector of Manager
oh, also because it is public, unity might try to serialize it. i wonder if that is the problem
is Data marked as Serializable?
you probably also want [NonSerialized] public Data data = new();
its 0
wym?
if it is serializable, Unity may try to save the old Data value you have stored
which is wrong here
nope still 0
you have a public variable data in a Monobehaviour, that means Unity will try to serialize it if the class is marked as serializable
yes but i did NonSerialized before data and still same error
try to call Debug(cost.Length); in the constructor for Data
we want to clear out all the bad things it could be, even if itâs not the cause for this specific issue
I still want to see the Inspector of Manager
this?
yeah, it isnât serialized, which is good
i get this ArgumentNullException: Object Graph cannot be null. Parameter name: graph System.Runtime.Serialization.Formatters.Binary.ObjectWriter.Serialize (System.Object graph, System.Runtime.Remoting.Messaging.Header[] inHeaders, System.Runtime.Serialization.Formatters.Binary.__BinaryWriter serWriter, System.Boolean fCheck) (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0) System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph, System.Runtime.Remoting.Messaging.Header[] headers, System.Boolean fCheck) (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0) System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph, System.Runtime.Remoting.Messaging.Header[] headers) (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0) System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Serialize (System.IO.Stream serializationStream, System.Object graph) (at <17d9ce77f27a4bd2afb5ba32c9bea976>:0) SaveSystem.<SaveData>g__Save|6_0[T] (System.String path, SaveSystem+<>c__DisplayClass6_0`1[T]& ) (at Assets/Scripts/SaveSystem.cs:30) SaveSystem.SaveData[T] (T data, System.String filename) (at Assets/Scripts/SaveSystem.cs:21) Manager.Update () (at Assets/Scripts/Manager.cs:188)
if you put Debug.Log(cost.Length) in Dataâs constructor, what is the result?
does anyone know about a better way to make a timer? I've been doing this for now:
m_milliseconds = Mathf.FloorToInt((m_pointsTimer % 1f) * 100); // m_pointsTimer is increased by Time.deltaTime every frame
if (m_pointsTimer - 1f >= 0) {
m_pointsTimer -= 1f;
m_seconds++;
if (m_seconds >= 60) {
m_seconds = 0;
m_minutes++;
}
}
m_timerLabel.text = (m_minutes < 10 ? "0" : "") + m_minutes + ":" +
(m_seconds < 10 ? "0" : "") + m_seconds + "." +
(m_milliseconds < 10 ? "0" : "") + m_milliseconds;
I need a better aproach or a built in Unity timer because at game over I have to decrease the timer down to 00:00.00
coroutine
the msg above
and you get that when you press play?
yeah but I have to display it, coroutines wont work because of that
Data..ctor () (at Assets/Scripts/Data.cs:20)
``` and still 0
coroutines can work. and you probably want to use ToString formatting arguments
and this is when Debug.Log is put AFTER you assign cost = new⊠?
and data = new() only once when you declare data?
yes i think so
but the constructor is being called, because you see the debug log
i also removed NonSerialized and now no errors and var is now 2
yes
its fixed now, tysm
interesting, the documentation says nothing about UnityEvent<bool> đ€Ż where did you learn this? also is UnityEvent<bool, int> also possible? And UnityEvent<bool, int, int> etc depending on how many parameters your method has?
i would also make data a property.
public Data data {get; private set; }
automatically not serialized, and data canât be assigned in different places
alright thak you for all your help
then click on the set keyword, and ctrl+R (or ctrl shift R?) to find all references to it
so you can make sure it is only assigned once
alright thx
gl
Ah shit sorry for the late reply
I was very busy
Did you figure it out?
Also, guys, should I use an object pool?
For the muzzle flash?
Here
why can't i access this public void on my button's On Click event?
https://hastebin.com/share/zujevevawa.cpp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
so i tried adding another array but it doesn't work, i get the same issue as above, when its starts its set to 0 but the other one does work
public void Textfix()
{
if (data.cost[0] >= 1000 && data.cost[0] < 1000000)
{cost1Text.text = "Money: " + (data.cost[0] / 1000).ToString("F2") + "k";}
if (data.cost[0] >= 1000000 && data.cost[0] < 1000000000)
{cost1Text.text = "Money: " + (data.cost[0] / 1000000).ToString("F2") + "M";}
if (data.cost[0] >= 1000000000 && data.cost[0] < 1000000000000)
{cost1Text.text = "Money: " + (data.cost[0] / 1000000000).ToString("F2") + "B";}
if (data.cost[0] >= 1000000000000 && data.cost[0] < 1000000000000000)
{cost1Text.text = "Money: " + (data.cost[0] / 1000000000000).ToString("F2") + "T";}
if (data.cost[0] > 1000000000000)
{cost1Text.text = "Money: " + (data.cost[0] / 1000000000000000).ToString("F2") + "q";}
if (data.lvl[0] < 1000) ///this line
{lvl1Text.text = "Money: " + data.lvl[0].ToString("F1");}
if (data.lvl[0] >= 1000 && data.lvl[0] < 1000000)
{lvl1Text.text = "Money: " + (data.lvl[0] / 1000).ToString("F2") + "k";}
}```
```C#
public class Manager : MonoBehaviour
{
public Data data {get; private set; }```
```C#
[Serializable]
public class Data
{
public BigDouble money;
public BigDouble[] cost;
public BigDouble[] lvl;
public Data(){
money = 0;
lvl = new BigDouble[] {0, 0, 0};
cost = new BigDouble[] {10, 125};
Debug.Log(lvl.Length);
}
}```
why is data serializable? should it be?
yes its cause everything is stored there for save system
use debugger then, to look into it
because it has 3 parameters
the UI only supports one parameter
put a breakpoint and look at wtf is in data during textfix
textfix is just so its like 100M 1B those stuff and i need to check how much is inside those vars to know wether its in millions or smt like that
also debugger i tried that but i can't find any solution
same error as before but its all the same
debugger doesnât mainly show errors. debugger should let you see the contents of variables
get in there and look at the contents of data
The predefined type 'System.Runtime.CompilerServices.IsExternalInit' must be defined or imported in order to declare init-only setter
What does that mean
Oh, it seems Unity does not support records like this
You can't use record I believe . . .
The docs should have a specific example on using record with Unity . . .
It's the primary constructor that is the problem.
Hi, I'm having an issue with my camera controller which you can see here: https://gdl.space/metemicame.cs . In particular, the GetCameraSize() function is the issue; As I say in the large comment at the top of the file, at step 5 I would like for this to return the smallest orthographic size where all the points can be seen. My issue is that this isn't working -> Not all the points can be seen. I'm sure it's just a tiny issue with my logic or something, but I can't pin point it. I would appreciate any help
It generates a property with an init setter, which is not supported in Unity. Except, the only thing missing is this System.Runtime.CompilerServices.IsExternalInit type. You can define it yourself.
unity doesnât support record keyword
Mmm, this is what I found:
Record support
C# 9 init and record support comes with a few caveats.
The type System.Runtime.CompilerServices.IsExternalInit is required for full record support as it uses init only setters, but is only available in .NET 5 and later (which Unity doesnât support). Users can work around this issue by declaring the System.Runtime.CompilerServices.IsExternalInit type in their own projects.
You shouldnât use C# records in serialized types because Unityâs serialization system doesnât support C# records.
Does this mean I need to import that package somehow to use records?
because Unity doesnât believe in new versions of C#. only some minor support
nope, Unity will not support it
Unity supports records, and can support init properties if you define this System.Runtime.CompilerServices.IsExternalInit type yourself.
unity has never supported records for me
Which version?
Eh.
Reserved to be used by the compiler for tracking metadata. This class should not be used by developers in source code.
Better leave my hands off this if the docs ask you to stay away
iâve been on the recent version i believe.
the data is set, but when the game starts it gets cleared
most recent as of June 2023
yeah. you set it to new
im lost rn
It's simply an empty type that the compiler relies on for metadata. There's no issue with defining it yourself.
do you want the Data field to get serialized in the Manager monobehaviour
Just a file with this is enough:
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit {}
}
then you definitely do not want to serialize it
Okay, I'll check it out!
Funny that Unity doesn't include those 3 lines then haha
then what do i need to change in my code?
click on the âsetâ keyword for data, and search all references
look for where it gets assigned
i think it is ctrl shift R on windows
or maybe ctrl R
weâre looking for every time data gets set
and we want that to be a single time
i want to use this function as a sort of buying mechanic for my cookie clicker game. i tried adding it to my buy button for my shop items however it seems that UI can only have one parameter in a function. how else would i go on about implementing buying items in my game?
https://hastebin.com/share/kamoxidefi.cpp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
what do you mean
click on âsetâ where you wrote private set
then ctrl+R
(or ctrl-shift-R, donât remember)
Ooh alright
now at the bottom of visual studio it should show you every time it is used
links to every line
Alr
what do you mean by only 1 parameter?
are you having issues with having 3 arguments to the function?
yes
well is this function in a monobehaviour?
yeah
It's probably not the best solution but why not try using a struct?
Button events can only use methods with one parameter when attempting to add a method from a MonoBehaviour in the inspector . . .
I don't mean to be rude, but I'm also still looking for some help regarding my own issue.
As SDS stated, you can creete a struct with your parameters as its fields, but you need to subscribe the method to the button listener via code . . .
okay ill try using a struct, thanks guys!
sorry i'm pretty new to structs. what would i need to put inside the struct? should i store my parameters in the struct and use a new method to call that struct?
struct="light weight" class
and you can treat it as class
I'm not exactly the most knowledgable but I think something like this should work:
[System.Serializable]
public struct ShopParameters {
[SerializeField] public int parameterName,
}
public void Buy(ShopParameters param) {...}
They are similar to creating a class but you use the struct keyword instead. You can find a tutorial online to give you an example. The fields of the struct will be the same names as the parameters for the method . . .
not sure if this is the right channel for this
for some reason i cant seem to do anything with TextMeshPro in code.
using TMPro; gives me this error: ```
error CS0246: The type or namespace name 'TMPro' could not be found (are you missing a using directive or an assembly reference?)
here's the package in package manager too :O
did you import tmp essential resources?
yep i get this when i click on it
did you like save your file maybe?
do you have an assembly definition in your Scripts folder?
well I have no clue then
sorry what assembly definition? :O
Any assembly definition
Do you have one or not?
Take a look
it would be a .asmdef file, it will look like a puzzle piece icon in project window
ok yea i got one
That's your problem
why is that there
either remove it, or add the TMP reference to it
you mean an asset?
its a project i cloned from github for embedded web browser
Sure but why are your scripts inside that package's asmdef?
It should be in its own folder
In fact it should have been imported as a package and not in your Assets folder at all
this sample unity project was setup in that github too
oh yea its separately in Packages folder
this is just a template project i was using since it was already setup đ
if it's in Packages you can delete the stuff from Assets
In any case there's absolutely no reason your custom script inside Assets/Scripts should be covered under this assembly definition
Hi I'm still looking for help in my problem thanks.
do you guys know how to use this function?
ForceMode.VelocityChange
that's not a function
it's a member of the ForceMode enum
Typically you use it with AddForce:
rb.AddForce(someForce, ForceMode.VelocityChange);```
oh i see, then how do you use it in the AddForce funtion?
as a parameter
ahh alr, ill try it out
is it only used for the y axis or can it also be used for the x axis as well?
i have no idea what this question means
it applies to the entire force
You provide the direction of force when calling the AddForce method . . .
so can you do this?
rb.AddForce(ForceMode.VelocityChange, someforce);
no
like this
You have to give the parameters in the order they're defined:
https://docs.unity3d.com/ScriptReference/Rigidbody.AddForce.html
Take a look at the unity docs for the method. It has examples and details on each forcemode . . .
wdym?
The first parameter has to be a vector I think, rb.AddForce(new Vector3(), ForceMode.VelocityChange)
You provide (enter) the direction of force. It can be on any axis: x, y, or z . . .
What do you think ForceMode.VelocityChange means
What are you expecting it to do
Because I do not think it means what you think it means
I think it adds the force on an object in a certain way. For example, ForceMode.Acceleration makes it accelerate where as ForceMode.Impulse interprets it as an impulse
Can someone please help me? I think I'm just messing up some simple logic but I can't pin point it
Yes that is correct but do you know what acceleration or impulse mean
You still have to give it a force. The force mode is not itself a force, it just determines how that force gets added
Hey
If I have an empty object acting as a group for objects to be a child of, if I want them all to behave like they are stuck together would I need to remove the rigidbody from all the children and give one to the parent instead?
Yes
ahhh I see, that makes sense
cheers, wasn't sure if adding one to an empty object would work since it doesn't have any physics properties
use a primative collider that surrounds the general shape of all ur pieces together
or.. keep the colliders u have..
can you use these different types of forces to avoid overwriting another force?
the rigidbody will take all child colliders into cosideration
Could probably do some complex/bizarre joint connection system with the bunch of rigid bodies as well - constrains the objects together.
hehe maybe a bunch of fixed joints might wor
No
Forces don't overwrite, they add
That's why it's called addforce
when i am trying to build my game for ios with unity then i am getting this error again and again and i am unable to fix it :
Linker command failed with exit code 1 (use -v to see invocation)
Every time you apply force to an object, you're giving it more force - direction can be negative but it's technically adding forces to the already existing force being applied to the object.
u could add a positive force.. and then add a negative force..
would likely be close to cancelling each other out
but probably never exact
damn I see. The thing is that I want to add a force when the player sudently changes dorections, but my move function is setting the velocity to a deffined speed, making the AddForce not adding any force.
anyone please ??
Then you will need to not do that
Doesn't sound like a coding issue, you should probably try moving your message to #đ»âunity-talk
it is set 2 times, in time there and 1 time here C# private void Start() { data = SaveSystem.SaveExists(dataFileName)/// this line ? SaveSystem.LoadData<Data>(dataFileName) : new Data(); data.up1 = 0; ///lastFocusTime = DateTime.Now; Debug.Log(data.lvl.Length); Textfix(); imageChange(offlineImage); } what do i change or do?
oh that's neat. So one rigidbody on the child should behave as I want it to
now for the moment of truth
welp
got close X/
You might want to summarize what you've done thus far and what the issue is.
so here is the thing thats going on now
How can I force screen orientation to be landscape and lock orientation? Currently I have:
Screen.orientation = ScreenOrientation.LandscapeLeft; in my Start() but it doesn't seem to work
this was whats going on before
almost certainly oyu're dealing with an uninitialized serialized (aka all empty/default) copy of your class.
but without seeing more code it can't be said for sure
but weird thing is, i left my pc for 2h, did nothing and its F* fixed đ
I just restarted untity and all errors are gone...
so ye thx for trying to help but im good now ig
but how? I tried playing around with the if statements, but will will always end up getting complicated, I am trying to find a simple way out
oh wait, is it possible to disable some functions and enable other functions?
because I was maybe I can enable a function at a specific moment and then let the other function do its thing after when a function has done its purpose
You'd get the entire set together (rigid body physics as a component)
I don't understand, what is a set?
The entirety of the rigid body physics system with the component
Its what digiholic told you. Dont set your velocity directly use AddForce
You should not mix setting the velocity and using add force. Setting the velocity will override any force applied . . .
Trying to make a wand moving around my player and when the mouse gets further I want the wand to go a bit further from the player and its the last line of code that is doing that. and for that I should just be able to twick the x value of the want and it works if I change it in inspeactor but for some reason that last line of code is also changing my y value Idk why
ahh I see, is there any diffrence between Adding forces and setting the velocity? I thought that adding forces makes the movement feel snappy where as adding forces makes the movement mode rolly, like a ball
You're assigning one of the values zero in the vector 3
You can think of it this way.
Setting velocity:
velocity = x;
Adding force:
velocity = velocity + force;
effectively they do the same thing - change the velocity
but adding force takes the current velocity into account and adds to it
the z
and the y
the y should keep being 0
and it changes
Im hella confused
Snappiness or not just depends on how much force you're adding and when.
first thing's first. Is this an orthographic camera or a perspective camera?
ok - you're being a little careless with your z coordinates here.
note that even in 2d, all these things will have a z coordinate
ah nvm you're using Vector2s everywhere.
If the y value is changing, maybe this function isn't occurring every frame to constrain the y value?
I'm trying to open the Ruby 2D Adventure Beginner tutorial on unity hub, but I can't open the assets on the store
This is the tutorial: https://learn.unity.com/tutorial/welcome-to-2d-beginner-adventure-game?uv=2022.3&courseId=64774201edbc2a1638d25d18#
The assets is called StarterAssets.unitypackage but when I try to add it to unity hub as a project, the file doesn't show up to be selected, and when I select the entire folder it says it is invalid.
I've tried opening the StarterAssets thing but it opens up unity start icon then it dissapears and nothing happens.
When I've gone on the website to download the assets, when I open it in the unity hub, the unity hub has a little loading screen then nothing happens.
Any help on how to open this tutorial? Thanks
This is the asset on the store : https://assetstore.unity.com/packages/2d/unity-learn-2d-beginner-tutorial-resources-urp-140167?utm_source=youtube&utm_medium=social&utm_campaign=education_global_generalpromo_2019-05-03_learn&utm_content=video_2d-beginner-project.
I'm not sure if this is different to the one on the tutorial page, but I can't manage to download it anyways.
Get the Unity Learn | 2D Beginner: Tutorial Resources | URP package from Unity Technologies and speed up your game development process. Find this & other 2D options on the Unity Asset Store.
In this introductory tutorial, youâll learn the following things: What this course is about. Who this course is for. How this course is structured. Youâll also have the opportunity to explore the example 2D adventure that we have created! By the end of the tutorial, you should know whether the 2D Beginner: Adventure Game course is right for yo...
but when I cut that line of code off it keeps being 0
yah I would just want it to be 0
should I set it 0?
nvm I think it's fine because you're explicitly using Vector2s
You've likely got something else going on
though you are definitely being a little inefficient with how you construct them
I just checked if I set the x value in that to a constant it stops moving with its parent object
not sure why
yah the parent of it moves
are you wanting all this stuff to be relative to the parent? You should use localPosition instead then
but be careful because the mouse pos is in world space
The values you see in the inspector are the local position and whatnot
ohhhhhhhhh
ok I will try using the localposition
so the position is like setting despiting there existing a parent?
yes
it's setting world position
if the parent is at +5 and you set position to 0, your local position will be set to -5
so setting localPosition to 0 I assume will align it with the parent?
thank you its almost working
yes I guess so
Currently got an issue where I can't drag a a group of objects around once they've merged. Got this for the drag and drop and I thought I needed to check whether a parent exists then set the transforms to that. I can move each individual one but once they've merged together I don't even get the mouseDown breakpoint reached
Yeah I click on them like this and they don't move like before
how would i subscribe a method to a button's onclick listener through code?
does the parent empty also need it's own collider for you to then be able to click on it?
Since it looks like the OnMouseDown method is never fired for me
button.onClick.AddListener(...);```
thanks
oh my, fixed it. Turns out I just needed to put my drag and drop script on the group empty object 
my word I think this is the messiest way of doing this possible
just the whole component and script system gets a bit tough to wrap my head around. Had to put the objectSnap script on this just so I could pass in an instance of it since I have a delegate that needs to be fired when two items snap 
surely this can't be how you are supposed to do it
well what does the ObjectSnap script do? Is it supposed to be on one of the snappable objects?
If so it doesn't make any sense to put it here
it's only supposed to go on the snappable ones, yes. I just couldnt figure out how I could make it so that the CreateNewStructure method runs since it needed a reference to the object snap
If you want the BuildManager to know when any objects snap, you would need to either:
- Switch to a static event and subscribe to that (and pass a ref to theobject in the event)
- have BuildManager dynamically subscribe to each snappable object (possibly by having them register themselves with the BuildManager in Awake)
but this seems to convoluted I know it's not the right way
so given this, I could just set that event to static it should work for the most part?
Hey I'm working on an FPS shooter where the enemy is controlled by AI. Whenever an enemy dies, a script should apply force to its rigidbody, but instead it doesnt do anything, what can go wrong? (death is made with ragdolls)
at first glance I'd assume it's cause rig doesn't have anything assigned to it in the inspector
hi guys how can i fix this the collider is not moving forward when the animation is playing, and when the animation finishes, the character goes back to the starting point of the animation and my collider and script in the Parent(BaykusEnemy) :/
On playtime it works
well you'd likely want to pass in the snapping object itself in the delegate
but yes, because then you can subscribe to the static event without an instance
the instance will come as a parameter
guys I still cannot solve this issue. I have a house prop. It has doors. When I add Mesh Collider for it, it closes all the house. I cannot go through the door. Is there only way to fix this by adding manually box colliders around all walls, roof ?
if you set the collider as convex it cannot have holes
to be perfectly honest, manually placing a few box colliders will probably be the most performant solution
if I set it to Convex then all physic props and me goes out after I hit Play button. Everything then is outside
if I have like around 100 house props now and every of them are the same.... this is the hardcore to play with box colliders đŠ how to do for the roof ? :/
Make it a prefab
you then only need to do it once
If you pass in the snap object in the delegate though, how can that work here since I need that object first before being able to call the actual method?
You shouldn't be calling it here at all
the ObjectSnap class should be calling it
yup, just make ya a box collider for the wall and add it to the building.. leaving a gap for the door
u want ur colliders as simple as possible for hte most part
hmmm Thanks PraetorBlue đ looks like i gonna have so much boring work đŠ
esp if u have lots of physics in ur game
not really
you make the prefab once
then stamp it around your world as many times as you want
yes but other houses ar not the same .... i have lots of different houses .... đŠ and all of them I plan to make enterable
ok well yes each one should be a prefab'
possibly prefab variants of some base house prefab
one prefab can contain other prefabs
how about that V form roof for bos collision ?
but the objectsnap class doesn't have the CreateNewStructure method.
I think i'll definitely do more research into this, struggling to figure it all out
u ever gonna be walkin across the roof?
Depends how accurate you need collisions to be
It doesn't need to, that's the whole point of the event
đ
letâs say you have a red wall and blue wall. these two should be prefab variants of a wall prefab.
letâs say you have a house with 4 walls. That should be a house prefab, which contains 4 wall prefab-connected objects in it
OR.. an alternative.. make the doorways a threshold.. that u load into..
then it drops u inside the house..
then no messy door colliders to mess with đ
but if I have a weather conditions, and there are no box colliders for the roof, it means that rain/snow will go into house ?
yup, this is just basic game developing trouble shooting..
if you aren't supposed to do this at all here then how is the method in here going to be fired?
do u turn off the weather while ur inside? if theres windows can you turn it off? does ur weather effects actually collide with things? etc etc
Example:
https://hatebin.com/sdhqvnleza
you can always define a zone with no weather, depending on how you make weather
its open world, you can explore, and weather doesnt change if youre inside
yea, but sometimes u have to deal with stuff like that for performance.. say ur inside a house with no windows.. or even better an underground tunnel..
i would then make a monobehaviour for a roof, which defines a region under it to block weather
why spend the resources running the weather when ur not gonna see it?
or monobehaviour for a house or something
why not keep track of what the weather was originally? u can turn it back on when u exit.. or get to the top floor
etc etc
hmmm đ
i think he means if you are looking outside door, you should see dry indoor and rain outside in one frame
but ya, its ur choice.. i like to disable stuff on the outside when ur inside
no need on using that extra resources
Just realised I've been a complete fool and forgot to reference the class. I really need a break...
true.. in that case id probably make tiny volumes to put in front of each window
depends on how you define weather tbh
facts
if every raindrop has a sphere collider, then just use colliders. but that shit will get expensive
đ
either way, you need some way to represent the volume where you expect no weather
but that is a very different question
Chat-GPT always has solutions đ
Certainly! If you want your player to collide with the house but still interact with doors using the 'E' key, you can use a combination of colliders and raycasting. Here's a simple example script:
Create a new script (e.g., DoorInteraction) and attach it to the player or an empty GameObject in the scene.
Set up Colliders:
Give your house GameObject a MeshCollider for collision with the player.
For the doors, you can use primitive colliders like BoxCollider or SphereCollider for each door.
Write the Script:
but i tried a lot of of its offers but none worked for that house PROP đ
i too believe in sphere colliders for doors 
đ
doors are always hard tbh. there are many videos detailing how to do doors
yep, different ways to do it, but still the house prop is my headache
graphics and interactions always seperate
member that and ur fine.. ur house prop is a graphic..
the colliders would be its own thing sharing a parent
u could keep mesh renderers and filters on it and enable and disable them as u need while building it out
when finished.. just remove all the mesh rendererer stuff. and keep the colliders
what's the hardest part about them?
the only time i have issues with doors is when i want them physically accurate and try to use unity's hinge joints
đ
3 things make doors hard. 1) Loading/spawning things, 2) colliders meeting at a sharp angle and moving with a hinge, and 3) graphics on each side of the door
i animate my doors.. always have them open outwards, simple solution
or sliding doors.. (#sci-fi)
japanese sliding doors are extremely easy to implement relative to doors with hinges
lol..
does anyone know why transform.pos has other value than it should have? When i set it to an int, it s auto adding 0.5
at least I'm prepared for what would lie ahead when I need to work on them in the future đŹ
or metroid prime energy doors that just appear / disappear entirely
bead doors are even easier
even doors are beyond what I can realistically do at the moment
ok, I see You guys are active today. How do I bake NavMesh for my big terrain ? ..... is it possible to bake like manually ?
i can feel the GPU melting
Hitman Absolution
or do what SC Chaos Theory does
a game object can exist simply as a means of utilizing scripts, correct? or are they explicitly intended to be "physical" objects within the scene?
have most doors be fabric ones you walk through
u described a basic "GameManager"
I must have spent at least 2 minutes doing this before recording.
oh fck that
lmao
how do they do that i wonder?
verlet rope sim?
with some colliders spaced out
prob just a bunch of hinges
xD
does look cool tho
im not so sure now that they changed the navmesh stuff
u could usually mark ur stuff as static / navigation and inside the navigation window u could click bake
and it would run a bake manually.
just do realtime baking
is a navmesh always required for any ai to be able to walk on it?
gotcha
if you want proper A* and RVO
saw a gdc talk about that a little while ago but I've not looked into it much yet
A* is the shit
The value you see in inspector is local position, the debug is world position
hmmm navarone , you mean when I Play game, i bake it to terrain surface ?
its wat unity uses.. but u can get assets/ external repo's that have much more for A*
u can have flying enemies for example with no nav mesh
ty
for big terrains prob easier than a giant navmsesh
you bake as you walk
maybe you have a quick tutorial for that ?
i would walk onto the playable area only
ah unity nuked the page without replacement..smart
yeah
wondered how that'd work with flying ones. I imagined creating a navmesh as a sort of volume would be the solution but that sounds rather strenuous
same link lol
đ
Learn how to bake a NavMesh on a small portion of your level. This allows much faster baking of NavMeshes on large procedural worlds, or on very large worlds. We do this by specifying a volume around the player and use the NavMeshBuilder class to collect the relevant sources and update a registered NavMeshData.
If you are taking this concept a...
this dude has the best Navmesh agent videos
already watching
I think they moved quite a few tutorials into Pathways courses and never redirected properly.
Still can be found on YouTube Unity channel though
most of the flying enemy stuff ends up being custom
depending on whetehr ur making a 2d gmae, 3d game, or w/e
if you have a game that is primarily text-based other than basic icons to represent a character or item, etc., in what form does an item possessed by the player 'exist'? Like if the player has an AK-47 rifle, but that rifle is only really represented as an inventory icon and a +3 attack bonus, how should you bring that rifle into 'existence' i.e. when the character comes to actually possess it? Specifically if you want to be able to add a scope for a +1 attack bonus (it seems a lot of people use scriptable objects for inventory items but as I understand it you cannot edit their variables at runtime and thus cannot at the scope for +1 attack for example)
this is absolutely practical for smaller 2d type platformers
make the graphics bob up and down above the capsule đ
thats howI faked some drone enemies, but in 3d
so could you just use a game object even though the object doesn't need to be represented physically within the scene?
Often I would use a reference to a ScriptableObject that describes the weapon. The SO may itself have a reference to a prefab that you could instantiate to bring it into the real world, as well as a reference to a sprite to show it in the inventory UI for example
the navmeshagent doesnt need the collider right above the ground mesh does it?
im wondering how ud walk beneath it?
There's nothing stopping you from wrapping the SO reference in another object at runtime to apply things like this
for example
class InventoryWeapon {
WeaponSO baseweapon;
List<Modifier> modifiers;
}```
looks like that guy wrote his own NavMesh Bake script
absolutely..
i just put the actual collider on the mesh/graphic, so it can easily go under stuff
when people talk about seperating graphics from logics thats what they mean... the graphics are a seperate part of the piece.. if u remove them completely u basically have an invisible object (holding all the logic)
and there is nothing "wrong" with this in terms of best practices?
no, not that i can think of... how else would u run logic in the game, without the chunk of code being in the game itself somehow
Hey guys I'm on the create with code 2 unit and am getting this error and I've checked all over up and down to try and see where the (almost certainly) syntax error is and I just can't find it.
Difficulty Button https://paste.ofcode.org/3bhXhbSgwNXWY6EQJXRvvNk
GameManager https://paste.ofcode.org/mmmkXGWihTJbzBg42DUdEG
Error Message: Assets\Scripts\DifficultyButton.cs(26,21): error CS1061: 'GameManager' does not contain a definition for 'StartGame' and no accessible extension method 'StartGame' accepting a first argument of type 'GameManager' could be found (are you missing a using directive or an assembly reference?)
any help would be appreciated
right, and I guess what I'm trying to clarify my understanding on is that even though I have a weapon defined within my script(s) for example, it doesn't really exist within the game until it's attached to an object... is that right?
did you save all of your scripts?
ya, it has to be inside the hierarchy to run..
unless ur code sepcifically references it some other way
yes
this is a common way to enable and disable stuff
say u have a Gun.. u can keep that object attached to the player and disabled..
once u enable it.. (u can enable the graphics with it) and the logic (the code that works the gun)
wait. no the game manager script wasn't saved
and voila you have a gun object
lol
that'll do it too đ
uggggggggg just save both scripts with one save lol. thanks though
for example my GameManager runs alot of things in the game but as u can see in the scene view..
obligatory "use cinemachine"
its just an empty gameobject sitting at (0,0,0)
Iâm quite new to c# but Iâm pretty sure your Lerp is wrong
are those empties literally only there to create space in the list?
affirmative
fair enough
Itâs jumping to the final position because you have the return value set immediately
once im closer to finished product ill go back and delete most of em
well your lerp is FPS dependent. the more frames you have, the faster it will lerp
because each one is keeping track of a transform..
also from the links you've all sent here I've come to realise that my game dev tips and tutorials youtube playlist is growing incredibly large
its a waste of performance.. (not alot) but it'll add up
so when its time ill remove em
they add up đ
i was thinking the same..
ur lerp should be continuously running i think..
in a seperate loop or something..
I tend to find one good tutorial, check out the person who made it and then save like 15 of their other vids including the start of other playlists. It's a rabbit hole i tell you
Yes
i bet all that happens at once.. during the keypress.. and it doesnt have time to smooth
It can but that's not how you've coded it. You made it just be at 20% between start and end
Pretty sure you set the percentageComplete in a while loop and call the lerp in a separate function
Then use percentageComplete as your 3rd parameter
Let me get on my computer and I can show you the way Iâve been coding lerps, 1 sec
MoveTowards ftw
the issue wasn't where the Lerp call was. it was the fact that you were moving 20% of the way from startPosition to finalPosition each frame so after 5 frames it's already there
Give me 1 sec mish I will show you
read the overview and the wrong lerp section in that link to learn how to correctly use lerp
also when working with rotations, you probably want slerp instead
oops
oh and you are lerping a value you use to rotate rather than the rotation itself which is odd
void SmoothRotate(Vector3 rotationAmount)
{
// Calculate the target rotation
Quaternion targetRotation = Quaternion.Euler(rotationAmount);
// Store the current rotation
Quaternion currentRotation = Camera.main.transform.rotation;
// Slerp the current rotation towards the target rotation
Camera.main.transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, rotationSpeed * Time.deltaTime);
}```
edit: i still dnt think this is completely correct, Im bad at lerps too đ
how do i view and edit a struct in the inspector?
float percentageComplete = 0;
while (percentageComplete < 1)
{
yield return null;
percentageComplete += Time.deltaTime / 4;
lerpFunction();
}
void lerpFunction()
{
gameObject.transform.rotation = Quaternion.Lerp(Quaternion.Euler (startAngle), Quaternion.Euler (endAngle), percentageComplete);
}
make it serializable and then you have to have a variable of that type that is serialized on a component
@queen adder this is how i've been lerping, dont know if it's the best but it works
Are back ticks not a thing on mobile? Straight up canât find them
note that this will only work in a coroutine
oops, didn't add that
this probably depends on your device and the keyboard you use on said device. and is entirely unrelated to unity or coding
i tried that but it doesnt work for some reason
click the symbols button
then you did something wrong and should share what you tried
and then its on the 2nd page of them
click the 1/2 button
it lists more
and its in the middle left
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
you didn't mark the struct as serializable or have a variable of that type in your component
so the only two things i said you need to do were ignored
Canât spot em, will look em up later on, not too important. Just didnât want to paste loads of stuff without it being in a code block
2nd one to the right on top row
use a third party website its easier
for example
oh okay ill try that. also what do you mean by having a variable of that type in my component?
i mean that you need a variable of type ShopParameters in your BuyItem component
there wouldn't be any serialized variable of that type without it
[System.Serializable]
public struct ShopParameters
{
}```
public class ShopManager : MonoBehaviour
{
public ShopParameters shopParams;
boxfriend is the MVP i just follow
Can somebody please explain why I'm getting this error?
The code works exactly like it should
AI_Script is null
you likely have one of those components in the scene where AI_Script has not been assigned in the inspector. or you are overwriting its assignment somewhere
That's it thanks
also unrelated to your code issue, but the inconsistent naming conventions, namely the seemingly random inclusion of Snake_Case, is kind of annoying. standard c# conventions don't use snake_case at all, types should typically be PascalCase, class variables either camelCase or PascalCase depending on their access modifier, and local variables as camelCase
Thanks for the feedback, I know a lot of people would disagree with my choice but I never use camel case, I use pascal for everything other than constants
well you're still randomly using Snake_Case which is the biggest issue with your naming here
the most important thing is that you are being consistent. which you are not
What is an easy way to snap cubes together? Imagine the default cube, put one in the middle, then I pick up another cube and instantiate it on the cursor, now I want it to snap to all 4 sides on the Z and X axis to that cube (or any other cube) only and when pulling the cube close to that cube it snaps into the side so they always form a perfect grid. Pretty much like holding down V in the editor
Any variables which are not pascal are typos
then AI_Script, AI_Weapon_Enable, and your class names are typos
every new word is caps, how is that not pascal?
PascalCase does not use underscores between the words. that is only done in snake_case. and that's been my entire point this whole time
Ohh right I see, well I must have gotten the two mixed up
naming conventions are something I never had in mind
since all my projects are solo so only I need to understand my way of coding
you are right though I should start doing it the industry standard way
i'm not even saying to follow the standard coding conventions. i'm saying you should at least be consistent with your naming conventions.
but if you do want to follow the standard conventions then check this out https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions
public class BoardService : Service, ICardSearchable
public interface ICardSearchable
{
public bool CardsExist()
Why can I not call BoardService.Instance.CardsExist (it doesn't find CardsExist)
is CardsExist a default interface method where the implementation is defined in the interface, or does the BoardService class define the implementation?
No only the interface defines it
that's why. only variables of the interface type will have that method on them. you can't even just call CardsExist within the BoardService class without casting to ICardSearchable first
does this still work?
it is recommended to instead use the CompareTag method rather than string equality when checking tags
but otherwise, yes it does still work
Mmm. Maybe I'm approaching it wrong, but this is what I want:
In a card game, there are different locations where cards can be (deck, hand, board, etc.).
All of these have services that are ICardSearchable. That interfaces demands that the service should implement
protected IEnumerable<CardSO> CardSet(); as a way to get the set of cards of that location (the hand for example has a list of cards, the deck as a stack of cards, and so on).
CardsExist itself is but an algorithm that shouldn't change for any card location. It should be available to outside methods.
That's all you need to do. If it's not showing up, you probably have a compile error.
Unity won't use your new code until there are zero compile errors.
then what am I doing wrong?
well, your syntax is wrong
col not collision
Your curly braces are messed up
I want to move object smoothly when collision enter. I cant do this with * time.deltaTime since its only in 1 frame. How can I do this?
okay well your issue is that BoardService does not implement the method, it's on the interface. you could case BoardService.Instance to ICardSearchable to be able to call that method. or you could instead move the implementation of the method to the class instead of the interface.
@desert elm
you could use a coroutine
i should point out that there's nothing special about Time.deltaTime here
wdm nothing special?
you're asking how to do something over several frames; you could do this without factoring in deltaTime just fine
you are absolutely going to use Time.deltaTime.
Oh
I cant do this with * time.deltaTime since its only in 1 frame.
This is just a weird thing to say, which is why I brought it up.
oh right forgot those for the method
I see the issue
Mmm, that seems like a strange limitation in C#. I shouldn't have to "redefine" a method in a class.
The reason I don't want to move the implementation to the class is that if the algorithm changes, I would have to change the implementation in every single class, instead of just one in the interface.
C# does not permit multiple inheritance
Interface implementations are not inherited.
They're strictly only accessible through the interface type itself.
this is how default interface methods work. they do not exist on the class, they only exist on the interface therefore you need a variable of the interface type to access them
It's useful for ensuring backwards-compatibility when adding members to an interface
have a look at this.
So my best choice is to just do something like public bool CardsExist() =>CardsExist(); ?
no, because the CardsExist implementation only exists on the interface type. If you want to access the interface method, you'd need to cast this to the interface type and then call the method on it.
what you wrote would just be infinite recursion
that is an infinite loop
Oh I think I get it. So a class that implements a public method does not know that it has that public method?
It absolutely does.
it does
Interface methods aren't virtual
but multiple classes can have that interface
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PressurePlate : MonoBehaviour
{
[SerializeField] Transform interactObject;
private void OnCollisionEnter(Collision collision)
{
StartCoroutine(Move());
}
private void OnCollisionExit(Collision collision)
{
interactObject.position -= Vector3.up * 2f;
}
IEnumerator Move()
{
interactObject.position += Vector3.up * 2f * Time.deltaTime;
yield return new WaitForSeconds(2f);
}
}
@swift crag I dont know if it is what u meant
so, you know how enemies in mario can spawn from spawnpoints or pipes or blocks or billblasters?
So more like this: public bool CardsExist() => ((ICardSearchable)this).CardsExist()
spawnpoints and pipes need to know if what they spawned died, so things that get spawned need some some of reference to the thing that spawned it to let it know.
actually, let me take that back. that was incorrect.
but they are all totally different, so i would make an ISpawner interface. Then anything that is spawned holds an ISpawner. ISpawner has public void OnSpawnedThingDied();
My pipe, spawnpoint, bill blaster, and block all have a behaviour that implements ISpawner. They do different things when OnSpawnedThingDied() is called
It was unrelated to what you were doing.
pipe needs to check if it was at its spawn limit. spawnpoint needs to know to turn off forever. block doesnât care. and bill blaster knows to turn back on.
When you implement an interface, you must provide a concrete implementation of every method in the interface.
Default interface methods allow you to not implement a certain method. The default is used if you don't provide one.
I think my issue was that I did not think of casting. It should be a nice implementation if I just cast to the interface and call that method đ
Indeed. That will work.
and all the enemies or whatever that spawn do not care what kind of thing spawned them. they just have a reference to an ISpawner
It does lead to some annoying copy-pasting
does this make sense?
Can someone explain to me why its not working?
This coroutine sets the position once.
It then waits for 2 seconds before ending.
That doesn't sound like what you want.
Do I have to somehow do the "disenvoke" for the event? Or it's a one-time trigger thing?
Not asking about unsubscribing, only about if there's opposite to .Invoke()
then you'll need to set the position many times.
I do not understand what you mean. You can't.."un-invoke" a method, for sure
interface can define a common non-virtual implementation in itself btw
right, that's the default interface method.
U can by CancelInvoke()
yes, the default implementation was what was being discussed
Oh yeah, haven' thought about that as a method đ Okay, you solved that for me, thanks )
that's unity's Invoke method
which lets you send a message to an object after a delay
i think AA is gone rn.
yeah, I meant UnityEvent
yeah, Invoke will run the method exactly once
sorry, it's a bit of html talking in me. IF we open the tag, we better close it at some point )
Or if we instantiate some game object, we better destroy it after it's no longer needed. That was the question basically.
I do not understand.
no wonder, because it's silly question
I think one has to be a bloody noob to understand what I am asking đ
Guys, should I use an object pool here to optimize the muzzle flash effect?
why are you spawning new one each time?
wildly unnecessary
It's a prefab holding all the particle data
unrelated to my statement
I'm just creating an instance of said prefab since all the particles play on awake anyway
I don't know how else to apply said effect
well, you will need to create one burst of particles per shot
Itâs a #đ»âcode-beginner , theyâre not in here if itâs easy for them xD
ps.Emit()
so for loop
yes, đ better to start early to do it right
You can then call Emit on them to make them spit out particles on-demand
You might need to switch the particle system to use world space, not local space, if you weren't parenting each of those systems to the gun.
i made an ai enemy that can go so distances and chase us when we close to it, but when i changed its position now it is not working
Otherwise, the effects will appear to be stuck to the gun
what is "not working"
And I can provide with my code
i mean it has moving animation but doesnt change position
it was working
before i changed its position
So I dont really have to use time.deltaTime?
Since I have to repeat this code
you sound confused about what deltaTime tells you
let me explain in a thread
time.deltaTime measures the time between every frame
whereas just time is fixed to real-time
i send a video about it to unity-talk
Set each particle system to emit no particles. It's in the "Emission" tab in the inspector.
Then attach this prefab to the end of the gun and leave it activated.
Add ParticleSystem fields to your weapon component and drag the references in.
And then?
When you fire, call Emit on each particle system
the number you pass is how many particles spawn, so you'll need to pick a good number for each one
I tried making a public ParticleSystem variable before but it didn't let me drag objects that were in the scene but only prefabs
Prefabs can't refer to scene objects, yes
but it sounds like you already have a weapon prefab here
do all of this setup on the weapon prefab.
particle systems are trial and error for me.. sometimes u can nest the 2ndary particles under the root.. and fire off the top one..
all the ones below will follow suit
So how must I drag in the particle systems into the inspector if it won't let me do it directly from the hierarchy?
You're going to need to clarify what you're doing.
Do you not have an instance of this prefab attached to the gun?
Nope
well, do that!
Prefabs
if the prefab needs to reference something in the scene, you either need to have the thing start in the scene with the references ready to go..
or grab teh refernences during runtime
after the prefab starts to exist
Gun inspector
You're not going to be instantiating the prefab over and over anymore.
You're going to have one instance on the gun
it will already exist; it's not being created by your weapon code
i got a new bug that seems intresting, my character is NOW stuck at 0, 0
Something like that! Here's how I would do it
better to use an array than numbered variables!
Alright, thank you
[System.Serializable]
public struct ParticleInfo {
public ParticleSystem system;
public int count;
}
[SerializeField] List<ParticleInfo> particleInfos;
void Shoot() {
foreach (var info in particleInfos) {
info.system.Emit(info.count);
}
}
Now you can make a list of particle systems and how many particles you want to emit!
Then I attach the particle systems into the gun's hierarchy?
nice and neat, no recompiling needed every time you want to change a number
You'd attach your prefab to the gun, yes
and then reference its particle systems
If you did this, you'd set the "Particle Infos" list to hold 3 elements, then drag the particle systems into each one
just fire off hte top most particle.. the child particles will fire also
it seems so weird but im not too sure if its the player controller or something else
and then punch in how many particles to emit from each one
Done
if u attach it to firepoint u can save urself the trouble or moving everything
Yeah, you should align it properly.
just move the firepoint , the particle system will follow
Yo! I have a small problem and I don't really know how I can find a workaround. I use a CharacterController and I apply gravity like so :
private Vector3 playerVelocity = Vector3.zero;
private float gravityValue = -9.8f;
playerVelocity.y += gravityValue * Time.deltaTime;
And it works fine. The problem is, if the CharacterController is close to the ground but less than 9.8 units from the ground it will stop falling while not touching the ground. I guess that's because if the CharacterController fall another 9.8 units it will be in another object and the CharacterController doesn't allow you to cross objects. But I want my character to fall until it touches the ground. How can I do that ?
My fire point is in front of the player, but my FXPoint makes it look like it's firing from the barrel
Easier to deal with ADS
9.8 meters shouldn't come up here -- you only accelerate by a tiny bit each frame
fixed it
I need to see how you're reading the velocity back from the player controller
use !code to share large scripts
đ 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.
large code blocks up top
I turn it off completely or??
Yes.
You're going to use Emit() to emit particles.
ah, so you reset playerVelocity if you're on the ground
Right, of course
I don't think it has anything to do with your code. I think your CharacterController is probably just not aligned with the Renderer on your character
That'd be my guess
The default makes you float, since the capsule is centered on the origin
Don't know if this help you
private void ApplyGravity()
{
// if our controller is grounded and our simulated gravity is less than the gravity we defined
if(characterController.isGrounded && gravitySim < playerSettings.gravity)
gravitySim = playerSettings.gravity;
// we set it back to the defined value
// to simulate gravity we keep adding scaled gravity to the player (the above conditional keeps it clamped for us)
gravitySim += playerSettings.gravity * Time.deltaTime;
}```
this is my gravity function... if im grounded i keep it constant
if im not.. i added my force
ScriptableObject inventory: One has to create item database in order to save the data.
Do I have to make skill database in order to save the data about the scriptable object skills that characters have?
I think the problem is what I said in my first message. But I'm new so I'm probably wrong
making sure ur order of logic fits ur needs is important too..
i get my input, then i do my ground check, finally i use all the information ive gathered to move the player appropriately
Did you see the picture ?
could u make a video, or screenshot what it looks like
the picture shows that ur graphics (the ball thing) is aligned to the bottom of ur capsule.
but its also not in play mode..
You want me to show it in playmode ?
I think I understood it after reading the documentation.
Something like this should theoretically work, correct? ```cs
private void EmitParticleSystems()
{
if (system1 != null)
{
system1.Emit(1);
}
if (system2 != null)
{
system2.Emit(1);
}
if (system3 != null)
{
system3.Emit(1);
}
}
from the screenshot alone to me it seems the ground's collider doesn't match up with teh actual ground plane
if you ever find yourself differentiating variables only by adding a number ot the same name, you should be using some sort of collection like a List or array
i can kinda see the wall behind to the right.. also floating a bit off the ground
Yes, I've seen this suggestion and I'll implement it directly after playtesting. Thank you
Yes but it's not supposed to. And I guess the problem is that in this exact situation the CharacterController can't substract 9.8 because the CharacterController will be in the ground.
but nothing like urs
But I don't know what to do xD
That might just be the Skin Width
Guys uhh
If I manually move my character the thing works
Don't know if it help
The problem is the gravity don't do its job
Do you guys use gtag fan games
Gravity is working fine. Itâs just that thereâs a slight margin around the collider
The character controller doesnât give up if it sees an obstacle. It moves as far as it can.
^ what he said... ur lookin for the error in the wrong place
@swift crag , the emit system works nearly flawlessly, only issue is that it doesn't follow the rotation of my weapon
I ran into this recently
And how should I correct that ?
Move your character visual down
u have to use local rotations and not world rotations
thers a setting in there where u change the particles simulation space
Brilliant! Thank you
or.. it could be the facing direction.. if that doesnt work..
With the space on Local, the smoke will stick to the gun
But this will change nothing ?
The visual doesn't have any hitbox
yea, thats what i was thinkin after i said it.
If the problem is that youâre floating slightly, this will fix your problem
This has nothing to do with the ground being âin the wayâ for that last little bit of falling
the player basically thinks its grounded now..
If the problem isnât fixed, please show us a video
thats fine, just move the graphics to be TRUELY groundewd
Will do
This is my character. I don't understand what you want me to do
sure, if that works out when ur player is moving about
I would suggest restructuring a bit
- Player <- has the CharacterController
- Model <- has the renderers and stuff
Alternatively, change the center of the controller a bit.
graphics should be decoupled from the logic
I create an empty game object named Model and child "Md_Char..." and "Root" ?
you should be able to change out the graphics whenever u want, and it not affect the controller at all
Yes I can do that
ahh then it shuld be fine.. if u can make sense of the hiearchy then thats all that matters
Is "Player" a prefab created from a model you imported?
Yes
unless ur showing it around askin for help, then it may confuse others..
and is "Md_Char_Low_Poly_Man" an object with a skinned mesh renderer?
If so, then you need to parent "Player" to a new game object
and put the controller on that new object
Yes
Ok
^ this happens beacuse the controller has a little extra "padding" around it
the thickness is based on the Skin Width
This helps it to collide properly and avoid getting stuck.
i just noticed that in my own game. time to fix that!
Like this then ?
Still happening
(English isn't my first language so i'm probably not understanding what you want me to do)
!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.
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public PlayerScriptableObject playerObject;
public GameObject playerGameObject;
public Rigidbody playerRigidbody;
public float maxVelocityChange = 4f;
float currentMoveSpeed;
float xInput;
float yInput;
// Start is called before the first frame update
void Start()
{
currentMoveSpeed = playerObject.movementSpeed;
}
// Update is called once per frame
void Update()
{
GetPlayerInput();
MovePlayer();
PlayerRotate();
}
void GetPlayerInput()
{
xInput = Input.GetAxisRaw("Horizontal");
yInput = Input.GetAxisRaw("Vertical");
if(Input.GetKey(KeyCode.LeftShift))
{
currentMoveSpeed = playerObject.sprintSpeed;
}
else
{
currentMoveSpeed = playerObject.movementSpeed;
}
}
void MovePlayer()
{
Vector3 moveDirection = new Vector3(xInput, 0f, yInput).normalized;
Vector3 force = moveDirection * currentMoveSpeed * Time.fixedDeltaTime * 1000f;
force = Vector3.ClampMagnitude(force, currentMoveSpeed);
playerRigidbody.AddForce(force);
}
void PlayerRotate()
{
//stuff
}
}
Hi there I have this code for a player movement in 3D. However when the player moves its slightly jittering, any way to solve this?
how would i go on about checking if the player has bought a specific item using this approach?
https://hastebin.com/share/ifafocikaj.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Now move "CharacterModel" down a little
The controller will still look like it's floating a little.
But the model's feet will be on the ground.
@swift crag It works!! Thank you for your help. I appreciate it
Yes. That will compensate for the skin width.
Physics based movement should be done in FixedUpdate
also MovePlayer is needlessly complicated, forces shouldn't be multiplied by deltatime and it looks like ClampMagnitude is there just to fix the problem that it causes
But it still doesn't count as grounded
I copied an old Unity code snippet and im getting this error :
was there previously a namespace named carManager ?
Thank you!
Perhaps you need to change where you do your grounding check as well.